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
其实不太能懂你的提问,那咱就来用思路走一遍这个代码吧
myFunction.bind(myObject)进入到原型得bind函数内部
将myFunction赋值给fn,将参数转化成一个数组args,将第一个参数删除并赋值给object。
返回一个函数,然后你思考下闭包这回事,然后就了解。这个函数干的活可以简单得理解为myFunction.apply(myObject,[...这里是其他参数])
aFunction()
就是myFunction.apply(myObject,[...这里木有参数])
然后进入到myFunction内部,因为apply的关系this就是myObject,然后干的活就是myObject==myObject
返回true