Javascript call() & apply() vs bind()?

后端 未结 22 1927
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

22条回答
  •  醉话见心
    2020-11-22 03:39

    Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

    Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

    I do this a lot:

    function MyObject(element) {
        this.elm = element;
    
        element.addEventListener('click', this.onClick.bind(this), false);
    };
    
    MyObject.prototype.onClick = function(e) {
         var t=this;  //do something with [t]...
        //without bind the context of this function wouldn't be a MyObject
        //instance as you would normally expect.
    };
    

    I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

    A simple, naive implementation of bind would be like:

    Function.prototype.bind = function(ctx) {
        var fn = this;
        return function() {
            fn.apply(ctx, arguments);
        };
    };
    

    There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

    Hope this helps.

提交回复
热议问题