bind()方法創建一個新的函數(稱爲綁定函數), 當被調用時,將其this關鍵字設置爲提供的值,在調用新函數時,在任何提供之前提供一個給定的參數序列。
// bind方法是複製的意思,參數可以在複製的時候傳進去,也可以在複製之後調用的時候傳入進去
// apply和call是調用的時候改變this指向
// bind方法,是複製一份的時候,改變了this的指向
this.name = 'jack'; // window的this
var demo = {
name:'rose',
getName: function(){
return this.name; // demo的this
}
}
console.log(demo.getName()); //輸出rose 這裏的this指向demo
var anot = demo.getName;
console.log('jack'+anot()); //輸出jack 這裏的this指向全局對象
var anot2
anot2 = demo.getName.bind(demo);
console.log('rose'+anot2()); //輸出rose 這裏this指向了demo對象了
注意,如果demo對象的getName方法寫成箭頭函數,這個this就是指向外部的this
var demo = {
name:'rose',
getName: () => {
return this.name;
}
}
裏面有很多例子
https://blog.csdn.net/qq_32849999/article/details/80472417