我正在尝试了解javascript bind
方法。我已阅读this other SO post about bind方法并学到了很多东西。其中一个链接到javascripture的帖子,我在那里使用了bind。
根据我的理解,并根据mozilla's site,绑定“创建一个新的函数,将'this
绑定到绑定对象。”
var Button = function(content) {
this.content = content; //stores content into this.content property
};
Button.prototype.click = function() { //adds click method
console.log(this.content + ' clicked');
}
var myButton = new Button('OK');
console.log(myButton.content); //OK
myButton.click(); //OK clicked
var looseClick = myButton.click;
console.log(looseClick.content); //undefined
looseClick(); //undefined clicked
var notLooseClick = myButton.click.bind(myButton);
console.log(notLooseClick.content); //undefined
notLooseClick(); //OK clicked
我的困惑是最后一个变种notLooseClick
。我不明白为什么notLooseClick.content
会在undefined
返回notLooseClick();
时返回'OK clicked'
。我原本期望'OK'
被绑定到notLooseClick.content.
如何绑定notLooseClick
,因此当我致电notLooseClick.content
时,它会绑定到按钮this.content
,因此当我输入notLooseClick.content
时,它会返回'OK'
?为什么bind()
表现得这样?
答案 0 :(得分:1)
你误解了Function.bind
的作用。它确保在调用函数时,this
将是您传入的任何内容。它不会将对象的任何属性复制到您绑定的函数中。
var Button = function(content) {
this.content = content; //stores content into this.content property
};
Button.prototype.click = function() { //adds click method
console.log(this.content + ' clicked');
}
var okButton = new Button('OK');
// This calls click using okButton as its `this`
okButton.click();
var looseClick = okButton.click;
// This calls the same click function without specifying a `this`
// It will be window or null if on strict mode
looseClick();
// Here you are saying:
// No matter how this function is called, it will always use okButton as its `this`
var boundClick = okButton.click.bind(okButton);
boundClick();
您似乎认为bind
函数会使您的函数从绑定它的对象继承属性。但这不是它的作用,它会在通话中绑定this
。
var notLooseClick = myButton.click.bind(myButton);
// It's undefined, you didn't copy properties of myButton to notLooseCLick
console.log(notLooseClick.content); //undefined
// Here it works because you've set `this` in calls to notLooseClick to be myButton
notLooseClick();