how to simply make a reference to this
(the obj
) in this simple example? (and in this exact case, using obj. literal)?
http://jsfiddle.net/YFeGF/
var obj = {
planet : "World!", // ok, let's use this planet!
text : {
hi: "Hello ",
pl: this.planet // WRONG scope... :(
},
logTitle : function(){
console.log( this.text.hi +''+ this.planet ); // here "this" works !
}
};
obj.logTitle(); // WORKS! // "Hello World!"
console.log( obj.text.hi +''+ obj.text.pl ); // NO DICE // "Hello undefined"
I tried also making that : this,
but again that
is undefined inside the inner object
Do not use object literal, use function approach,
var Obj = function(){
var self = this; //store self reference in a variable
self.planet = "World!", // ok, let's use this planet!
self.text = {
hi: "Hello ",
pl: self.planet
};
self.logTitle = function(){
console.log( self.text.hi +''+ self.planet );
}
};
var obj = new Obj();
console.log( obj.text.hi +''+ obj.text.pl );
obj.logTitle();
Here is working jsfiddle : http://jsfiddle.net/cettox/RCPT5/.
Read this great MDN article on Object Oriented Javascript too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With