"this" explicit binding using "bind" function example from YDKJS

Hello,
I have a question about how “this” explicit binding and how works in general the next example of code:

function foo(something) {
	console.log( this.a, something );
	return this.a + something;
}

// simple `bind` helper
function bind(fn, obj) {
	return function() {
		return fn.apply( obj, arguments );
	};
}

var obj = {
	a: 2
};

var bar = bind( foo, obj );

var b = bar( 3 ); // 2 3
console.log( b ); // 5

When we return bind(foo, obj) our bar object should equal function() { return fn.apply(obj, arguments); }. But on the next line we pass an argument 3 to bar, bar(3). But how I understand bar is an object function that do not take any argument? Or how it’s work exactly?

Thank you.

Unlike many other languages, you can pass as many arguments to a JavaScript function as you want. If you pass more arguments than you have named parameters, the remainder will mostly be ignored. All arguments reside in the arguments object, which is an array-like. This can be passed directly to function.prototype.apply, as you see in the example, because apply takes an array (or array-like) of arguments for the function being called.

function foo() {
    console.log(arguments);
}
//call without arguments
foo(); //Arguments []

//call with random arguments
foo(1,2,3,4,5,"dog", {name:"woobang"}); //Arguments [1, 2, 3, 4, 5, "dog", {name: "woobang"}]
1 Like

Thanks for information. I read about “arguments” object and how we can use apply to pass an array of arguments and how I understood we can use “arguments” to list them and use as we need.
For sure I’ll try to declare explicitly function parameters. At least for me it’s more convenient.
P.S.: Interesting to check if strict-mode insist to explicit declaration of function parameters.