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

后端 未结 22 2278
醉话见心
醉话见心 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:41

    Both Function.prototype.call() and Function.prototype.apply() call a function with a given this value, and return the return value of that function.

    Function.prototype.bind(), on the other hand, creates a new function with a given this value, and returns that function without executing it.

    So, let's take a function that looks like this :

    var logProp = function(prop) {
        console.log(this[prop]);
    };
    

    Now, let's take an object that looks like this :

    var Obj = {
        x : 5,
        y : 10
    };
    

    We can bind our function to our object like this :

    Obj.log = logProp.bind(Obj);
    

    Now, we can run Obj.log anywhere in our code :

    Obj.log('x'); // Output : 5
    Obj.log('y'); // Output : 10
    

    Where it really gets interesting, is when you not only bind a value for this, but also for for its argument prop :

    Obj.logX = logProp.bind(Obj, 'x');
    Obj.logY = logProp.bind(Obj, 'y');
    

    We can now do this :

    Obj.logX(); // Output : 5
    Obj.logY(); // Output : 10
    

提交回复
热议问题