Chaining 'bind' and 'call' in JavaScript?

后端 未结 3 1113
梦毁少年i
梦毁少年i 2020-12-06 18:34

When I reading this answer, find var g = f.call.bind(f);. I can\'t understand this with my first sight.

So does it has some direct meaning, and has some

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 19:12

    var g = f.call.bind(f);. I can't understand this with my first sight.

    I assume you're familar with both the .call() and .bind() Function methods? Well, it binds the f.call method to the function f.

    Notice that f.call is just Function.prototype.call, it doesn't matter that we access it as a property on f because we don't call it here.

    So does it has some direct meaning?

    It might become more obvious when we look at the ES6 equivalent:

    (Function.prototype.call).bind(f) // or
    (f.call).bind(f) // is basically
    (...args) => f.call(...args) // or more clear
    (ctx, ...args) => f.call(ctx, ...args)
    

    Does it have some appropriate usage scenarios?

    Well, now that you know what it does, yes. It can take a prototype method and transforms it to a static function that takes the instance as the first argument. An example:

    function Example(n) { this.name = n; }
    Example.prototype.display = function() { console.log(this.name); }
    
    Example.display = Function.call.bind(Example.prototype.display);
    
    var e = new Example;
    e.display(); // is the same as
    Example.display(e);
    

    Are there any laws for further chaining call/apply/bind?

    Yes: as always, only the last property in the chain is actually called as a method. In the above example, theres no difference between f.call.bind(…), Function.prototype.call.bind(…) or Function.call.apply.bind.call.bind(…) - it always calls bind on call.

    However, by passing them as arguments to each other, you can do some crazy things which are more or less useful.

提交回复
热议问题