Welcome to WebmasterWorld Guest from 54.158.228.55

Forum Moderators: open

Message Too Old, No Replies

accessing objects within object and object/functions

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

5+ Year Member




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 Sep 20, 2013 (gmt 0)

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



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 Sep 20, 2013 (gmt 0)

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




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
 

Featured Threads

Hot Threads This Week

Hot Threads This Month