Javascript attribute object property inside an object callback

I am trying to set an object (summary) inside another object callback method

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
}

The above code is not working (i.e. summarynot set to returnObj)

However, if I have the same code outside the callback method, it works as in the code snippet below:

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
}

I don’t know why this is so.

+4
source share
2 answers

You need to access your object with this , also I fixed some typos:

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);

Update: Added a code snippet to check availability returnObjthrough this in the callback handler.

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>
Run codeHide result
+5

this :

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

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

console.log(res.summary)

. jsfiddle

+1

Source: https://habr.com/ru/post/1623912/


All Articles