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

Javascript setting object property inside object callback

本文关键字:对象 设置 属性 回调 Javascript      更新时间:2023-09-26

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

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
}

不确定为什么会这样。

您必须使用这个语句访问您的对象,我还纠正了一些拼写错误:

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>

只需在对象内部使用this

var res = {
  foo: 'bar',
  setSmth: function(data) {
    this.summary = data
  }
}
res.setSmth({bar: 'foo'})
console.log(res.summary)

请参阅jsfiddle