Store reference to `call` function

前端 未结 2 938
[愿得一人]
[愿得一人] 2020-12-21 21:22

I noticed something curious earlier today. I can\'t seem to store a reference to the call property of a function, then execute it. Example:

var          


        
相关标签:
2条回答
  • 2020-12-21 22:10

    You need to keep the binding to console. Try this:

    var logCall = console.log.call.bind(console.log);
    // example: logCall(console, "foobar");
    

    or

    var log = console.log.bind(console);
    // example: log("foobar");
    

    For a bound reference to log.

    Edit: jsfiddle: http://jsfiddle.net/67mfQ/2/

    0 讨论(0)
  • 2020-12-21 22:16

    This is my favorite code in JavaScript:

    var bind = Function.bind;
    var call = Function.call;
    
    var bindable = bind.bind(bind);
    var callable = bindable(call);
    

    You can use the bindable function to grab a reference to f.bind. Similarly you can use the callable function to grab a reference to f.call as follows:

    var log = callable(console.log, console);
    

    Now all you need to do is call the log function like any other function:

    log("Hello World!");
    

    That's all folks.

    0 讨论(0)
提交回复
热议问题