[英]Store the “call”-function of a function in a variable
为什么以下各项无法按预期工作?
> function Double() { return this * 2; }
undefined
> Double
[Function: Double]
> Double.call
[Function: call]
> Double.call(8)
16
> var double = Double.call;
undefined
> double
[Function: call]
> double(8); ////// BAM! Why does this not work ??
TypeError: object is not a function
at repl:1:1
at REPLServer.defaultEval (repl.js:129:27)
at bound (domain.js:271:14)
at REPLServer.runBound [as eval] (domain.js:284:12)
at Interface.<anonymous> (repl.js:277:12)
at Interface.EventEmitter.emit (events.js:101:17)
at Interface._onLine (readline.js:194:10)
at Interface._line (readline.js:523:8)
at Interface._ttyWrite (readline.js:798:14)
at ReadStream.onkeypress (readline.js:98:10)
>
*编辑*
我创建了一个函数ref()来实现这一点:
Function.prototype.ref = function() {
var that = this;
return function(thisArg, args) {
return that.call(thisArg, args);
};
}
现在Double.ref()是一个可传递函数,其中第一个参数是this。
因为当您这样做时:
var double = Double.call;
您会失去Double
的上下文。 因此,当您调用double
它期望一个函数的上下文(因为那是Function.prototype.call
需要的),并且找不到它。
为了更简单地说,您试图在不是Function.prototype.call
上调用Function.prototype.call
。
您可以通过Double.call
的引用绑定到Double
来使其工作:
var double = Double.call.bind(Double);
double(8); // 16
为了进一步说明正在发生的事情,您可以使用对Function.prototype.call
任何引用,而不仅仅是通过Double
获得的引用:
var double = Function.prototype.call.bind(Double);
double(8); // 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.