题
下面是JS绑定的ES5shim。我不明白 自我.在绑定函数中应用。我知道如何使用apply方法,但在哪里 自我 指向在这种情况下?它应该是一个
功能,但在这里 自我 看起来像个物体。
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ), // self in this line is supposed
to // represent a function ?
args.concat( slice.call(arguments) ) );
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
解决方案
我记得在javascript 几乎一切都是一个对象。
所以你在那里有它:
self=这个
所以,自我不是表示,self 是实例。
其他提示
self
在你列出的垫片中使用,以适应以下事实: this
随范围变化而变化。功能的直接范围内。原型。绑定函数 this
将引用调用bind函数的对象。
一旦你进入嵌套的范围 bound
功能 this
已经改变了;所以作者已经分配了 self = this
内的 bind
函数允许的值 this
当时 bind
被要求继续提供给 bound
通过词法范围(闭包)函数。
JavaScript中的作用域可能会变得非常复杂;详细的解释请看这篇文章。
不隶属于 StackOverflow