简体   繁体   中英

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:

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.

Because when you do this:

var double = Double.call;

You lose the context of 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.

To try and put it more simply, you're trying to invoke Function.prototype.call on something that isn't a function.

You could make it work by binding the reference to Double.call back to 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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