Javascript设置对象回调内的对象属性

时间:2016-01-12 10:52:04

标签: javascript jquery

我正在尝试在另一个对象的回调方法

中设置一个对象(摘要)
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
}

不确定为什么会这样。

2 个答案:

答案 0 :(得分:5)

你必须使用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>

答案 1 :(得分:1)

在对象中使用this

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

res.setSmth({bar: 'foo'})

console.log(res.summary)

请参阅jsfiddle