What is the use of the JavaScript 'bind' method?

后端 未结 19 2395
自闭症患者
自闭症患者 2020-11-21 06:24

What is the use of bind() in JavaScript?

19条回答
  •  甜味超标
    2020-11-21 06:40

    From the MDN docs on Function.prototype.bind() :

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    So, what does that mean?!

    Well, 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
    

    This works, because we bound the value of this to our object Obj.


    Where it really gets interesting, is when you not only bind a value for this, but also 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
    

    Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

提交回复
热议问题