0

I'm creating a method inside of an object literal that relies upon passing the 'this' value of the object literal inside of a self invoking function. A simple example would be:

var obj = {
  whoAmI: function(){console.log('I\'m this: ' + this + ' object that exists with it\'s own scope')},

  getThis: (function(self){return self})(this)
}

console.log( obj.whoAmI() ); // shows the value of this as the object literal

console.log( obj.getThis );  // logs the window object to the console

I understand that the object literal creates it's own disposable scope, but I'm surprised that I could not pass the value of 'this' from the object literal as a parameter to the anonymous function.

dtothefp
  • 1,364
  • 1
  • 16
  • 22
  • 1
    you call the anon before the obj is done parsing. if you wait to call it, _this_ will be the obj object – dandavis Aug 17 '14 at 22:20
  • http://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function – Donal Aug 17 '14 at 22:21
  • During the time the object is created, it doesn't exist yet. You can't pass the `obj` there (and you can't expect that `this` would have the object literal's eventual value). – Bergi Aug 17 '14 at 23:04
  • @Bergi thanks this is exactly what I need http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations#answer-4616273 – dtothefp Aug 18 '14 at 14:29

0 Answers0