1

I have such a simple code

var q = {
  p1: 'kv3',
  p2: 'http://google.com/' + this.p1
};

console.log(q.p2);

which I expect to output the p2 + p1, but for some reason the p1 seems to be undefined when I console.log. Isn't p1 initialized before p2?

What would be the correct code for this?

1
  • this is only set when you call a function. Commented Feb 25, 2016 at 23:05

3 Answers 3

3

Remember that this is does not suddenly refer to q inside of the object declaration:

var p1 = 'kv3';

var q = {
  p1: p1,
  p2: 'http://google.com/' + p1
};
Sign up to request clarification or add additional context in comments.

Comments

2

The object q is initialised all in one, so everything inside it is inaccessible until the whole thing is done initialising. Try this:

var q = {
    p1: 'kv3'
};
q.p2 = 'http://google.com/' + q.p1

console.log(q.p2);

Comments

2

this is an additional parameter that functions (except arrow ones) receive when they are called.

Therefore, that this does not refer to the object (it has not been created yet anyways).

But you can instantiate an anonymous function instead:

var q = new function() {
  this.p1 = 'kv3';
  this.p2 = 'http://google.com/' + this.p1;
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.