gpt4 book ai didi

javascript - 我无法理解这个 javascript 函数是如何工作的

转载 作者:行者123 更新时间:2023-12-03 00:30:11 25 4
gpt4 key购买 nike

我正在阅读function definition of bind ,但我不能 100% 理解所写的代码:

if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}

var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();

return fBound;
};
}

具体来说,我不明白fNOP的用途,也不明白为什么需要设置fBound的原型(prototype)。我也被 fToBind.apply 部分挂断了(我无法弄清楚这在这种情况下代表什么)。

有人可以解释一下这是怎么回事吗?

最佳答案

嗯,需要设置 fBound 原型(prototype)的原因之一是,在函数上调用 bind 的结果与该函数具有相同的原型(prototype)。这也是 fNop 似乎发挥作用的地方 - 它允许您使用 new fNop() 设置 fBound 的原型(prototype),而无需调用原始函数这可能有副作用。

调用 apply 可以让您在函数中设置 this 并指定其他参数。由于 bind 允许您将参数“柯里化(Currying)”到函数中,因此您必须将绑定(bind)函数时传入的参数和调用函数时使用的参数结合起来。

关于javascript - 我无法理解这个 javascript 函数是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8809103/

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