我只是想真正理解以下来自 MDN 的代码。它是 Function.prototype.bind 的垫片:
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 && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
首先,为什么 aArgs 最初忽略参数列表中的第一个参数?
其次,为什么 fToBind 采用 aArgs 数组并在后面连接其余参数?这不会创建一个包含 args 1 到 n 和 args 0 到 n 连接的数组吗?
我很困惑!
最佳答案
First off, why is aArgs initially ignoring the first argument in the arguments list?
因为第一个参数是将 this
设置为 (oThis
) 的值。我们不想稍后将其作为参数传递给函数。
Secondly, why is fToBind taking the aArgs array and concatenating the rest of the arguments after? Wouldn't this create an array with args 1 to n concatenated with args 0 to n?
是的。请注意,这些是不同的参数集。 aArgs
指传递给 .bind()
的参数,而 arguments
指绑定(bind)函数的参数 fBound
。
我们想要传递已传递给 .bind
的参数和已传递给绑定(bind)函数的参数。 IE。我们想要
var fBound = f.bind(null, a, b); // aArgs = [a, b];
fBound(c, d); // arguments = [c, d]
等价于f(a, b, c, d)
。
基本上,它会执行所有操作,以便垫片像 .bind
预期的那样工作。如果您对实现感到困惑,您可能需要花费更多时间来更好地理解 .bind
。
关于javascript - 解释 Javascript 的 Function.prototype.bind 浏览器 shim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411310/