gpt4 book ai didi

javascript - mozilla 的绑定(bind)函数问题

转载 作者:行者123 更新时间:2023-11-30 06:39:53 25 4
gpt4 key购买 nike

我对我在 Mozilla 网站上找到的绑定(bind)函数的实现有疑问。在大多数情况下,这对我来说很有意义,但我无法弄清楚这张支票的用途...

this instanceof nop ? this : ( obj || {} ) 

在绑定(bind)函数中。显然它会检查“this”是否为空函数,但为什么需要绑定(bind)空函数。我已经在 Firebug 中试过了,它有效,但有什么意义呢?只是想增加我的 javascript 知识,所以我们将不胜感激。

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 || {} ),
args.concat( slice.call(arguments) ) );
};

nop.prototype = self.prototype;

bound.prototype = new nop();

return bound;
};
}

最佳答案

它允许您将绑定(bind)函数作为构造函数调用,而无需绑定(bind)到原始对象。换句话说,如果您使用 new 调用“绑定(bind)”函数,它仍然会像原始的未绑定(bind)版本一样工作。

这是一个例子:

var obj = {};

function foo(x) {
this.answer = x;
}
var bar = foo.bind(obj); // "always" use obj for "this"

bar(42);
console.log(obj.answer); // 42

var other = new bar(1); // Call bar as a constructor
console.log(obj.answer); // Still 42
console.log(other.answer); // 1

工作原理

为了简化解释,这里有一个简化版本的代码,它只绑定(bind) this 并且不处理参数或缺少的 obj 参数:

Function.prototype.bind = function( obj ) {
var self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : obj, arguments );
};

nop.prototype = self.prototype;
bound.prototype = new nop();

return bound;
};

Function.prototype.bind 返回的函数的行为会有所不同,具体取决于您将它用作函数还是构造函数(请参阅 ECMAScript 5 语言的 Section 15.3.4.5.115.3.4.5.2规范)。主要区别在于,当它作为构造函数调用时,它会忽略“绑定(bind) this”参数(因为在构造函数内部,this 需要是新创建的对象)。所以 bound 函数需要一种方法来确定它是如何被调用的。例如,bound(123)new bound(123) 并相应地设置 this

这就是 nop 函数的用武之地。它本质上充当一个中间“类”,因此 bound extends nopnop 又扩展了 self(调用函数 bind())。该部分设置在这里:

nop.prototype = self.prototype;
bound.prototype = new nop();

当你调用绑定(bind)函数时,它返回这个表达式:

self.apply( this instanceof nop ? this : obj, arguments ) )

this instanceof nop 通过遵循原型(prototype)链来确定 this 的任何原型(prototype)是否等于 nop.prototype。通过设置 nop.prototype = self.prototypebound.prototype = new nop(),任何使用 new bound() 创建的对象都将是通过 bound.prototype 使用来自 self 的原始原型(prototype)创建。所以在函数调用中,this instanceof nop(即 Object.getPrototypeOf(nop) == nop.prototype)为 true 并且 self 被调用使用 this(新创建的对象)。

在正常的函数调用中,'bound()'(没有 new),this instanceof nop 将为 false,因此 obj 得到作为 this 上下文传递,这是您对绑定(bind)函数的期望。

使用中间函数的原因是为了避免调用原始函数(在 bound.prototype = new nop(); 行),这可能会产生副作用。

关于javascript - mozilla 的绑定(bind)函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com