0

While defining an object in javascript, is there a way for a member of that object to access the value of another member of the same object? For example if I am defining the below (using jquery)

var x = $.extend({}, {
  greeting: 'hello',
  message: this.greeting+' world'
});

alert(x.message);

This above code would alert undefined world. How do I make it take the value of greeting during the definition. In this case the expected output is hello world.

Goje87
  • 2,689
  • 7
  • 27
  • 47
  • Related: http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – m90 Apr 18 '13 at 18:32
  • 1
    `this` in that case is the window, not the object, and since the object isn't defined anywhere yet, there isn't anything to reference yet. So, no, you can't do that. – Kevin B Apr 18 '13 at 18:33

3 Answers3

8

You can use properties:

var foo = {
    greeting: 'hello',
    get message() {
        return this.greeting+' world'
    }
};

console.log(foo.message);
foo.greeting = 'hi';
console.log(foo.message);

Although I'm not sure how these will interact with $.extend

In older browsers, you could always just make message a function, rather than a property getter

Eric
  • 91,378
  • 50
  • 226
  • 356
2

Try this way:

var x = $.extend({}, {
  greeting: 'hello',
  message: function(){
     return this.greeting+' world';
  }
});

alert(x.message);
Marcelo Rodovalho
  • 850
  • 15
  • 25
0

You can create some Constructor function. Inside this function this.greeting will be defined.

var Constructor = function () {
   this.greeting = 'hello',
   this.message = this.greeting + ' world'
   return this;
};

And then extend your object with instance of Constructor:

var x = $.extend({}, new Constructor());
Artyom Neustroev
  • 8,449
  • 5
  • 31
  • 55