Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this scope inside object literal [duplicate]

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

like image 203
Ginnani Avatar asked Oct 03 '22 00:10

Ginnani


1 Answers

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.

like image 103
Kemal Dağ Avatar answered Oct 10 '22 01:10

Kemal Dağ