pim*_*vdb 15 javascript bind function instanceof prototype-programming
在Mozilla开发人员中心,有一个关于该Function.prototype.bind功能的页面,并为不支持此功能的浏览器提供兼容性功能.
但是,在分析此兼容性代码时,我无法找出它们使用的原因instanceof nop.nop已经设定为function() {}.ECMA规范的哪一部分与bind此相对应?什么变量是一个实例function() {}?
以下返回false,因此我不完全知道它的用途.在做instanceof function() {}检查时会发生什么事情?
(function() {}) instanceof (function() {}) // false
Run Code Online (Sandbox Code Playgroud)
代码如下:
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;
};
Run Code Online (Sandbox Code Playgroud)
有人编辑了使其有用的部分.以下是它过去的样子:
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;
};
Run Code Online (Sandbox Code Playgroud)
我在这里回答了另一个问同样问题的问题(但代码是正确的):mozilla的绑定函数问题.
this instanceof nop检查的原因是,如果将绑定函数作为构造函数(即使用new运算符)调用,this则绑定到新对象而不是传递给的任何对象bind.
要解释"重要部分",nop基本上是插入到原型链中,这样当你将函数作为构造函数调用时,this 就是一个实例nop.
因此,如果您运行var bound = original.bind(someObject);原型链将如下所示:
original
|
nop
|
bound
我为什么他们用猜测nop来代替this instanceof self是使绑定功能,将有它自己的prototype特性(从继承self的).有可能它不应该是为什么它被部分编辑出来的原因.无论如何,现在的代码不正确,但只要您不将该函数用作构造函数,它就会起作用.