gpt4 book ai didi

javascript - 使用 "var that = this"了解 Javascript 作用域

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:05 24 4
gpt4 key购买 nike

<分区>

假设我在一个对象中有以下属性方法:

  onReady: function FlashUpload_onReady()
{
Alfresco.util.Ajax.jsonGet({
url: Alfresco.constants.PROXY_URI + "org/app/classification",
successCallback: {
fn: function (o) {
var classButtonMenu = [],
menuLabel, that = this;

var selectButtonClick = function (p_sType, p_aArgs, p_oItem) {
var sText = p_oItem.cfg.getProperty("text");
that.classificationSelectButton.set("label", sText);
};

for (var i in o.json.items) {
classButtonMenu.push({
text: o.json.items[i].classification,
value: o.json.items[i].filename,
onClick: {fn: selectButtonClick}
});
}

this.classificationSelectButton = new YAHOO.widget.Button({
id: this.id + "-appClassification",
type: "menu",
label: classButtonMenu[0].text,
name: "appClassification",
menu: classButtonMenu,
container: this.id + "-appClassificationSection-div"
});
},
scope: this
},
failureMessage: "Failed to retrieve classifications!"
});

我花了一些猜测才弄清楚,在 selectButtonClick 函数中,我需要引用 that 而不是 this 才能获得对 this.classificationSelectButton 的访问权限(否则出现 undefined),但我不确定为什么我不能使用 this。我最好的猜测是,在调用构造函数后,在 new YAHOO.widget.Button 中引用的整个对象中的任何属性都会以某种方式失去作用域。

有人可以解释一下为什么我必须使用 var that = this 来引用 classificationSelectButton 而不是仅仅调用 `this.classificationSelectButton' 吗?

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