在 Mozilla 开发者中心,有一个关于Function.prototype.bind https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind功能,并为不支持该功能的浏览器提供兼容功能。
但是,在分析此兼容性代码时,我无法找出他们为什么使用instanceof nop
. nop
已设置为function() {}
。 ECMA 规范的哪一部分bind
这对应于?哪些变量是一个实例function() {}
?
以下返回false
,所以我完全不知道它有什么用。执行以下操作时哪些内容会返回 trueinstanceof function() {}
check?
(function() {}) instanceof (function() {}) // false
代码如下:
Function.prototype.bind = function( obj ) {
if(typeof this !== 'function')
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ),
args.concat( slice.call(arguments) ) );
};
bound.prototype = this.prototype;
return bound;
};
有人编辑掉了有用的部分。这是它以前的样子:
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 || {} ),
args.concat( slice.call(arguments) ) );
};
// These lines are the important part
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
我在这里回答了另一个提出同样问题的问题(但是当代码正确时):mozilla的bind函数问题 https://stackoverflow.com/questions/5774070/mozillas-bind-function-question/5774147#5774147.
原因是this instanceof nop
检查是否将绑定函数作为构造函数调用(即使用new
操作员),this
绑定到新对象而不是您传递给的任何对象bind
.
为了解释“重要部分”,nop
基本上被插入到原型链中,这样当您将函数作为构造函数调用时,this
is的一个实例nop
.
所以如果你跑var bound = original.bind(someObject);
原型链将如下所示:
original
|
nop
|
bound
我猜测他们为什么使用nop
代替this instanceof self
这样绑定函数就有它自己的prototype
属性(继承自self
的)。这可能是不应该的,这可能就是它被部分编辑掉的原因。无论如何,现在的代码是不正确的,但只要您不将该函数用作构造函数,它就可以工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)