About Bind in Prototype JavaScript Language.

This is the first article on JavaScript, more will be put here in Chinese maybe.
Some reference is from the Prototype website, and some from JavaScript the definitive guide 5th edition, rest is my comment. hope this helps.

/*
“Binding” basically determines the meaning, when a function runs, of the this keyword.
While there usually is a proper default binding (this refers to whichever object the method is called on),
this can be “lost” sometimes, for instance when passing a function reference as an argument.

the execution scope is the object from which the function was called,
or (more precisely) the object that holds a reference to the function.
*/
bind: function() {
if (arguments.length < 2 && arguments[0] === undefined) return this; // if nothing to bind in arguments
/* following has a $A function call, basically reference the current argument or copy current argument into a newly created array. which maintain the value of the arguments for the binding function ^^ */
var __method = this, args = $A(arguments), object = args.shift(); // object set to the first element in the arguments
/*
The Array.concat() method creates and returns a new array that contains the elements of the original
array on which concat() was invoked, followed by each of the arguments to concat(). If any of these
arguments is itself an array, it is flattened, and its elements are added to the returned array. Note,
however, that concat() does not recursively flatten arrays of arrays.
*/
/*
Functions are objects in JavaScript, and apply allows you to apply the method of one object
in another object, which basically means your controlling the execution scope.
*/
return function() {
return __method.apply(object, args.concat($A(arguments))); // arguments here is newly passed in arguments, not the one above!
}
},

你可能感兴趣的:(JavaScript)