Javascript hard binding code snippet. (I dont understand the syntax of it)

Javascript hard binding code snippet. (I dont understand the syntax of it)
0

#1

I am reading YDKJS this and prototypes and here is a code snippet:

function foo(something){
	console.log(this.a,something);   //display the two numbers you got, one is this.a which is 2, 
//second is an argument that is currently vacant and waiting for input
	
	return this.a+something;	//add this 2 numbers up
}

var obj={a:2};//set the value of a

var bar=function(){return foo.apply(obj,arguments);}; //?

var b=bar(3);

console.log(b);

I understand that in this snippet, they wrapped a bar variable outside of the function call, just to create this so called hard binding and hence prevent this.a’s value changes to global variable.

What I dont understand is return foo.apply(obj,arguments); I dont understand the syntax of it. could someone explain it to me what does it do?


#2

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

Function.prototype.apply()


#3

@ArielLeslie

Does feel strange, but javascript functions are first class objects
It makes a lot more sense that it is a prototype method being called.
I am still new to JS, learned something today, ahead of schedule.


Thank you!
-WWC


#4

@ArielLeslie


#6

You are returning the foo function invocation with a

this

value that points to the global object

obj

The second parameter is an array of arguments which is what apply takes for its second argument.
Because you pass in a

this 

context you are able to reference the property

a

of the

obj

object.