Javascript 逗号运算符在这个来自MDN的多边形填充中做什么?
(粘贴在下面),使用逗号运算符。由于逗号运算符返回最后一个操作数,而第一个操作数(Javascript 逗号运算符在这个来自MDN的多边形填充中做什么?,javascript,polyfills,Javascript,Polyfills,(粘贴在下面),使用逗号运算符。由于逗号运算符返回最后一个操作数,而第一个操作数(oThis)不执行任何操作(如调用函数或赋值),因此它看起来毫无意义。但是我要假设MDN知道它在做什么,所以:在这种情况下逗号操作符做了什么有用的技巧? if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closes
oThis
)不执行任何操作(如调用函数或赋值),因此它看起来毫无意义。但是我要假设MDN知道它在做什么,所以:在这种情况下逗号操作符做了什么有用的技巧?
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, // <-- what's going on here?
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
它不是一个逗号运算符,而是一个逗号,用于分隔对
fToBind
的函数调用的参数。您可以重写为:
fBound = function () {
var args = aArgs.concat(Array.prototype.slice.call(arguments));
if (this instanceof fNOP && oThis) {
return fToBind.apply(this, args)
}
return fToBind.apply(oThis, args)
};
它等效于以下内容(除了分配给arg1和arg2的表达式在fToBind.apply之前进行计算,并且结果存储在变量中):
也就是说,逗号作为
apply
函数调用的参数分隔符存在,并且没有作为逗号运算符进行分析/实现。这是对apply
的调用,因此这只是传递两个参数,通常用逗号分隔…
fBound = function () {
var args = aArgs.concat(Array.prototype.slice.call(arguments));
if (this instanceof fNOP && oThis) {
return fToBind.apply(this, args)
}
return fToBind.apply(oThis, args)
};
var arg1 = this instanceof fNOP && oThis ? this : oThis;
var arg2 = aArgs.concat(Array.prototype.slice.call(arguments));
return fToBind.apply(arg1, arg2);