I think I may be missing something coming to object reference, in the below case, is this refering to the test object? If not how can I declare b so in the end test.a = test.b ?
test = {
a: 1,
b: this.a,
check : function(){
console.log(test.a); // returns 1
console.log(test.b); // returns undefined
}
};
test.check();
Thanks a lot
Jamiec
136k15 gold badges143 silver badges202 bronze badges
asked Nov 21, 2012 at 15:06
Dave Loepr
9661 gold badge7 silver badges13 bronze badges
2 Answers 2
You can declare it like this:
function test(){
this.a = 1;
this.b = this.a;
this.check = function(){
console.log(this.a); // output 1
console.log(this.b); // output 1
}
}
var t = new test();
t.check();
Live example: http://jsfiddle.net/Rqs86/
answered Nov 21, 2012 at 15:14
Jamiec
136k15 gold badges143 silver badges202 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Gurpreet Singh
new is keyword here. You need to create a new instance of test constructor in order to get desired output.
Dave Loepr
So if i get it correctly, you can not reference an object property declared within the same object scope level. I take this for solution, even if not, and Thank you for the demo aswell :)
test.b refers to whatever this.a was when declaring the object.
var foo = this;
You wouldn't expect this to refer to foo here, right? It works exactly the same here:
var bar = [ this ];
and
var baz = { 'blag' : this };
answered Nov 21, 2012 at 15:09
3 Comments
Dave Loepr
Thanks, this is useful to understand why this refers to nuts when b is declared. But then, how can i get b to build itself on top of a, basically a is a jquery object, and b is a property of this object. a: $('.class'), b:a.css() for example.
deceze
See @Jamiec's answer. Use a function which evaluates
this at call time, not at declaration time.Dave Loepr
Working too much with jquery the difference between declaration time and call time can seem blurry ;)
lang-js