Owen
Owen

Reputation: 4173

how to access javascript object from a function?

Let's say I have:

var test = {};
test.Data1 = {
    ...JSON objects here...
}; 
test.Data2 = {
    ...JSON objects here...
};
and so on... 

I usually access these json objects followed by a set of calls by:

this.scope.testData = test['Data1'];

However, may data for test is getting larger so i just wanted to pass whatever data i want to a function and do the processing like:

this.scope.setupData = function(data)
{
    var fData = test[data]; // is this line correct? 
    ...
    ...
    return fData;

};

but it's not working. I'm getting :Cannot set property "fData" of undefined to "[object Object]" ... I'm new to javaScript, any help would be appreciated.

Upvotes: 0

Views: 85

Answers (1)

Ast Derek
Ast Derek

Reputation: 2729

The problem is the scope inside this.scope.setupData. To access the variables relate to this.scope you need to use this again:

/**
 * At current scope, "this" refers to some object
 * Let's say the object is named "parent"
 *
 * "this" contains a property: "scope"
 */
this.scope.setupData = function(data)
{
    /**
     * At current scope, "this" refers to "parent.scope"
     *
     * "this" contains "setupData" and "testData"
     */
    var fData = this.testData[data]; // is this line correct? 
    ...
    ...
    return fData;
};

Upvotes: 1

Related Questions