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

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


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);


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?


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




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!




You are returning the foo function invocation with a


value that points to the global object


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


context you are able to reference the property


of the