The book JavaScript Ninja Secrets has a prototype library and an example of function bind code:
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,args.concat(Array.prototype.slice.call(arguments)));
};
};
var myObject = {a:"1"};
function myFunction(){
return this == myObject;
};
var aFunction = myFunction.bind(myObject);
aFunction();
I use breakpoints to check the functionbind
The fn inside points to myFunction
I don’t quite understand this function. My understanding is that just use Function.prototype
Prototype extension method The variable var fn=this;
in the declared variable fn=this;
points to the function using this method, just like myFunction in this example. bind(myObject);
Call the bin
method, fn
points to myFunction
I don’t know if this function is correct or not
迷茫2017-05-19 10:38:17
Actually, I don’t quite understand your question, so let’s walk through the code with ideas
myFunction.bind(myObject) enters the prototype’s bind function
Assign myFunction to fn, convert the parameters into an array args, delete the first parameter and assign it to object.
Return a function, then think about closures, and then you will understand. The work done by this function can be simply understood as myFunction.apply(myObject,[...here are other parameters])
aFunction()
It is myFunction.apply(myObject,[...there are no parameters here])
Then enter the inside of myFunction, because of the relationship between apply, this is myObject, and then the work is myObject==myObject
Return true