0

How can I reference a property of an object when creating the object itself? Example below which doesn't work:

var object = {

  prop1 : $(this).find('.foo');
  prop2 : this.prop1.find('.bar');

}
Paul
  • 139,544
  • 27
  • 275
  • 264
Chris
  • 1,557
  • 5
  • 19
  • 36
  • 1
    No, it's not possible (to reference the object - or properties therein - created by the object literal from within itself). Yes, this is a duplicate. – user2864740 Aug 01 '14 at 04:06
  • Sorry it's a duplicate. I did search. What is the common way around this? – Chris Aug 01 '14 at 04:07
  • Ahh, http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations , http://stackoverflow.com/questions/7433395/object-referencing-its-own-property-on-initilization?lq=1 – user2864740 Aug 01 '14 at 04:10
  • Also http://stackoverflow.com/questions/12396518/how-to-reference-a-key-from-the-same-object-when-creating-it?lq=1 , http://stackoverflow.com/questions/2787245/how-can-a-javascript-object-refer-to-values-in-itself?lq=1 – user2864740 Aug 01 '14 at 04:22

4 Answers4

0

You can use the new keyword with an anonymous function:

var $self = $(this);

var object = new function () {

  this.prop1 = $self.find('.foo');
  this.prop2 = this.prop1.find('.bar');

};

Technically that object will have a different constructor property than the object literal would, but that is unlikely to cause an issue for most use cases.

As a simple demonstration:

var obj = new function () {
  this.x = 7;
  this.y = this.x * 2;
};

console.log(obj); // Object {x: 7, y: 14} 
Paul
  • 139,544
  • 27
  • 275
  • 264
0

You can't refer a property of the object which is not yet created. You can have a function which will be called after the creation of object. So then you can refer a property using this.

Like bellow:-

obj = {
   a1:3,
   a2:function(){return this.a1}
};

so calling obj.a2() will return 3 here.

Or if you don't want to call is like a function use Get

obj = {
   a1:3,
   get a2(){return this.a1}
};

obj.a2; //returns 3

Basically what get does It binds an object property to a function that will be called when that property is looked up.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

This might be helpful

 var obj = {
 prop1 : $(this).find('.foo');
 prop2 : function() { return this.prop2.find('.bar'); }
};
0

I assume you're interested in avoiding recalculating $(this).find('.foo'), in which case you could do something like:

var object = (function() {

  var prop1 = $(this).find('.foo'),
      prop2 = prop1.find('bar');

  return {
    prop1: prop1,
    prop2: prop2
  };

}.bind(this);