0

Why does the following not work? According to everything I've read it looks like it should work?

a = {
  test: "hello",
  test2: this.test
};

I do a console.log(a) and I get test2: undefined.

user2864740
  • 60,010
  • 15
  • 145
  • 220
ABC
  • 1,387
  • 3
  • 17
  • 28
  • I'm not sure what you have read but maybe try something [different](http://amzn.to/1RNUZTi). In particular this [chapter](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/ch1.md). – Jason Cust Jun 30 '15 at 01:42
  • Your code is valid - check what this.test is just before a and it will also be undefined. – Brandon Smith Jun 30 '15 at 01:45

2 Answers2

1

In this example, this refers to the value of this relative to the statement a = ..., which is probably window (if you're running this in the browser, and if this is the entirety of the code).

If you wrote a constructor:

var A = function() {
    this.test = "hello";
    this.test2 = this.test;
};

var a = new A();

... the value of a.test2 would be what you'd expect.

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
0

Because your this refers to the window and there is no global variable/object named test, so window.test is undefined

I'm Joe Too
  • 5,468
  • 1
  • 17
  • 29