【发布时间】:2012-03-28 20:45:56
【问题描述】:
下面是一个用于 JS 绑定的 ES5 shim。我不明白 self。在绑定函数中应用。
我知道如何使用 apply 方法,但是在这种情况下 self 指向哪里?它应该是一个
函数,但这里 self 看起来像一个对象。
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;
};
}
【问题讨论】:
-
我知道这是一个古老的问题,但它在 Google 搜索分析中的排名很高。接受的答案非常具有误导性。我已经发布了一个带有一些额外细节的新答案。有兴趣的可以看看。