gpt4 book ai didi

Javascript 在对象回调中设置对象属性

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:44 24 4
gpt4 key购买 nike

我正在尝试在另一个对象的回调方法中设置一个对象(摘要)

returnObj.beforeLoadComplete = function (records) {
var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};

returnObj.summary = summaryObj;
// some other code which finally returns an object
}

上面的代码不起作用(即 summary 没有在 returnObj 上设置)

但是,如果我在回调方法之外有相同的代码,它会像下面的代码片段一样工作:

var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};

returnObj.summary = summaryObj;
returnObj.beforeLoadComplete = function (records) {
// some other code which finally returns an object
}

不知道为什么会这样。

最佳答案

您必须使用 this 访问您的对象声明,我还纠正了一些错字:

var returnObj = {};
returnObj.beforeLoadComplete = function (records) {
var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
// Access object with this
this.summary = someObj;
// some other code which finally returns an object
}
returnObj.beforeLoadComplete('records');
console.log(returnObj.summary);

更新:添加代码片段以验证returnObj 是否可以通过回调处理程序中的此访问。

var returnObj = {};
returnObj.beforeLoadComplete = function () {
var someObj = {
total: {
label: "Items",
value: "15"
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
this.summary = someObj;
// some other code which finally returns an object
}
//returnObj.beforeLoadComplete();

function verifyObjectUpdated(){
alert(returnObj.summary);
}
<select onChange="returnObj.beforeLoadComplete()">
<option>Trigger onChange to add summary to your returnObj</option>
<option>Trigger onChange to add summary to your returnObj</option>
</select>

<select onChange="verifyObjectUpdated()">
<option>Trigger onChange to alert summary of returnObj ( do it after adding summary)</option>
<option>Trigger onChange to alert summary of returnObj ( do it after adding summary)</option>
</select>

关于Javascript 在对象回调中设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34741700/

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