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

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

What is the use of bind() in JavaScript?

19条回答
  •  故里飘歌
    2020-11-21 06:43

    The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

       window.color = "red"; 
       var o = { color: "blue" }; 
       function sayColor(){ 
           alert(this.color); 
       } 
       var objectSayColor = sayColor.bind(o); 
       objectSayColor(); //blue 
    

    Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

    Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS

提交回复
热议问题