gpt4 book ai didi

javascript - 为什么javascript的bind()不自己绑定(bind)属性?

转载 作者:行者123 更新时间:2023-12-03 05:48:14 25 4
gpt4 key购买 nike

我正在尝试理解 javascript bind 方法。我已阅读this other SO post about bind方法,学到了很多东西。链接到 javascripture 的帖子之一我在那里玩了bind。

据我了解,并根据mozilla's site ,bind“创建一个新函数,将 this '绑定(bind)'到绑定(bind)对象。”

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 返回 undefinednotLooseClick(); 返回 'OK clicked'。我原以为 'OK' 会绑定(bind)到 notLooseClick.content。

如何绑定(bind) notLooseClick,以便当我调用 notLooseClick.content 时,它会绑定(bind)到 Button 的 this.content,因此当我键入时notLooseClick.content 它返回'OK'?为什么 bind() 会有这样的行为?

最佳答案

你误解了什么Function.bind做。它确保当调用函数时,this 将是您传入的任何内容。它不会将对象的任何属性复制到您绑定(bind)的函数。

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 函数将使您的函数从您绑定(bind)的对象继承属性。但这不是它的作用,它在调用中绑定(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();

关于javascript - 为什么javascript的bind()不自己绑定(bind)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40246309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com