Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, access other members during anonymous object creation?

Trying to get the following code to work; As the store variable is assigned an anonymous object, the "data" property is populated using a function call. This setting should also set the contents of the other object's property "masterData". I expected the "this" keyword to refer to the anonymous object being created, but I'm wrong...

    var store = {

        masterData : [],

        revert: function() {

            this.data = shallowCopy(this.masterData);
        },

        data: (function() {

            var overviewData = getOverviewData();
            this.masterData = overviewData;
            return chartData;

            }).call(),
    };

See also that "revert" property; It's given a function that'll create a copy of the object's data property contents.

What should be used, since "this" returns the DOMWindow object?

like image 514
Jem Avatar asked Oct 26 '25 06:10

Jem


2 Answers

The data function is being called before the object is defined; this will not be an alias to an object prior to that object's coming into existence. You can use a constructor function with a private, short-lived variable:

var getOverviewData = function () { return "I'm overview data!" }
var chartData = "I'm chart data!"

var store = new function () {
  var _masterData
  this.revert = function() {
    this.data = shallowCopy(this.masterData)
  }
  this.data = (function() {
    _masterData = getOverviewData()
    return chartData
  }).call()
  this.masterData = _masterData
}()

console.log(store)
// { revert: [Function],
//   data: 'I\'m chart data!',
//   masterData: 'I\'m overview data!' }
like image 147
Richard Simões Avatar answered Oct 29 '25 07:10

Richard Simões


i have the same problem and i solved it by just sending the scope with the function.

    var self = this;
    setInterval( yourFunction(self), 1000);

    yourFunction:function( self )
    {
        console.log(this);
        console.log(self);
    }

you see when it logs "this" it refers to the DOM and the self is refering to where ever you came from. i hope this helps! :)

EDIT: instead of inside Data to set the masterData, set the Master data after the Data is created.

var store = {

    masterData : [],

    revert: function() {

        this.data = shallowCopy(this.masterData);     //Here is where you create data
        masterData = this.data.overviewData;       //set the masterData
    },

    data: (function() {

        var overviewData = getOverviewData();
        return chartData;

        }).call(),
};

i think this should work, otherwise sorry :)

like image 30
Arjen van Heck Avatar answered Oct 29 '25 06:10

Arjen van Heck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!