homepage Welcome to WebmasterWorld Guest from 54.227.146.68
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
accessing objects within object and object/functions
camilord




msg:4611154
 3:59 am on Sep 20, 2013 (gmt 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..

 

Fotiman




msg:4611158
 4:27 am on Sep 20, 2013 (gmt 0)

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.

Fotiman




msg:4611159
 4:28 am on Sep 20, 2013 (gmt 0)


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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved