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

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

What is the use of bind() in JavaScript?

19条回答
  •  一生所求
    2020-11-21 06:33

    /**
     * Bind is a method inherited from Function.prototype same like call and apply
     * It basically helps to bind a function to an object's context during initialisation 
     * 
     * */
    
    window.myname = "Jineesh";  
    var foo = function(){ 
      return this.myname;
    };
    
    //IE < 8 has issues with this, supported in ecmascript 5
    var obj = { 
        myname : "John", 
        fn:foo.bind(window)// binds to window object
    }; 
    console.log( obj.fn() ); // Returns Jineesh
    

提交回复
热议问题