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

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

What is the use of bind() in JavaScript?

19条回答
  •  误落风尘
    2020-11-21 06:55

    Summary:

    The bind() method takes an object as an first argument and creates a new function. When the function is invoked the value of this in the function body will be the object which was passed in as an argument in the bind() function.

    How does this work in JS anyway

    The value of this in javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window (or global in nodeJS). Only call, apply and bind can alter the this binding differently. Here is an example to show how the this keyword works:

    let obj = {
      prop1: 1,
      func: function () { console.log(this); } 
    }
    
    obj.func();   // obj left of the dot so this refers to obj
    
    const customFunc = obj.func;  // we store the function in the customFunc obj
    
    customFunc();  // now the object left of the dot is window, 
                   // customFunc() is shorthand for window.customFunc()
                   // Therefore window will be logged

    How is bind used?

    Bind can help in overcoming difficulties with the this keyword by having a fixed object where this will refer to. For example:

    var name = 'globalName';
    
    const obj = {
      name: 'myName',
      sayName: function () { console.log(this.name);}
    }
    
    const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
    
    say(); // now because this function is executed in global scope this will refer to the global var
    
    const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
    
    boundSay();  // Now this will refer to the name in the obj object: 'myName'

    Once the function is bound to a particular this value we can pass it around and even put it on properties on other objects. The value of this will remain the same.

提交回复
热议问题