简体   繁体   English

将函数的“调用”函数存储在变量中

[英]Store the “call”-function of a function in a variable

why does the following not work as expected ? 为什么以下各项无法按预期工作?

> 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)
>

* EDIT * *编辑*

I've created a function ref() to achieve this: 我创建了一个函数ref()来实现这一点:

Function.prototype.ref = function() {
    var that = this;
    return function(thisArg, args) {
        return that.call(thisArg, args);
    };
}

Now Double.ref() is a passable function where the first argument is this. 现在Double.ref()是一个可传递函数,其中第一个参数是this。

Because when you do this: 因为当您这样做时:

var double = Double.call;

You lose the context of Double . 您会失去Double的上下文。 So then when you invoke double it expects a context of a function (since that's what Function.prototype.call requires) and doesn't find it. 因此,当您调用double它期望一个函数的上下文(因为那是Function.prototype.call需要的),并且找不到它。

To try and put it more simply, you're trying to invoke Function.prototype.call on something that isn't a function. 为了更简单地说,您试图在不是Function.prototype.call上调用Function.prototype.call

You could make it work by binding the reference to Double.call back to Double : 您可以通过Double.call的引用绑定到Double来使其工作:

var double = Double.call.bind(Double);
double(8); // 16

And just to further demonstrate what's happening, you can use any reference to Function.prototype.call , not just the one you got via Double : 为了进一步说明正在发生的事情,您可以使用对Function.prototype.call任何引用,而不仅仅是通过Double获得的引用:

var double = Function.prototype.call.bind(Double);
double(8); // 16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM