2

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

new is keyword here. You need to create a new instance of test constructor in order to get desired output.
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 :)
2

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

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.
See @Jamiec's answer. Use a function which evaluates this at call time, not at declaration time.
Working too much with jquery the difference between declaration time and call time can seem blurry ;)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.