Welcome to WebmasterWorld Guest from 23.20.184.141

Forum Moderators: open

Message Too Old, No Replies

accessing objects within object and object/functions

     
3:59 am on Sep 20, 2013 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 20, 2006
posts: 109
votes: 0



var test = {
var1: {varx: null, vary: null},
method1: {
submeth1: function (x) {
this.var1.varx = x'
}
submeth2: function() {
return this.var1.varx;
}
},
get_varx: function () {
return this.var1.varx;
}
}
test.method1.submeth1('my new value'); // the value
console.log(test.method1.submeth2()); // null
console.log(test.get_varx()); // null


------------------------

why is it returning null? how do i get and set the object?

please help.. thanks..
4:27 am on Sept 20, 2013 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4988
votes: 12


The code you posted above has a single quote at the end of line 5 that I think is supposed to be a semi-colon. Also, line 6 is missing a comma after the }.

But fixing those, then the problem is one of scope. When you call test.method1.submeth1, within the function this will refer to method1, not test. The same is true for the call to test.method1.submeth2.

If you want to call those with the scope of test, you could do this:
test.method1.submeth1.call(test, 'my new value');

Within the submeth1 function, this will then refer to the test object. Note, you'd also need to do the same thing for your call to test.method1.submeth2.
4:28 am on Sept 20, 2013 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4988
votes: 12



var test = {
var1: {
varx: null,
vary: null
},
method1: {
submeth1: function (x) {
console.log(this);
this.var1.varx = x;
},
submeth2: function () {
console.log(this);
return this.var1.varx;
}
},
get_varx: function () {
return this.var1.varx;
}
}
test.method1.submeth1.call(test,'my new value '); // the value
console.log(test.method1.submeth2.call(test)); // my new value
console.log(test.get_varx()); // my new value