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');
}
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');
}
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}
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.
This might be helpful
var obj = {
prop1 : $(this).find('.foo');
prop2 : function() { return this.prop2.find('.bar'); }
};
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);