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

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

What is the use of bind() in JavaScript?

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:56

    Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

    var x = 9; // this refers to global "window" object here in the browser
    var person = {
      x: 81,
      getX: function() {
        return this.x;
      }
    };
    
    var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
    
    var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
    
    document.getElementById("demo1").innerHTML = y();
    document.getElementById("demo2").innerHTML = x2();

    0

    0

提交回复
热议问题