0xSina
0xSina

Reputation: 21553

Javascript context confusion

I have this object:

var test = {
 setup: function() { property = 'hello!'; console.log(this); }
};

When I run test.setup(); and print out test.property(); it gives me undefined. I understand it's because I need to do this.property but my question is: why?

I can clearly see that the context is the test object via console.log(this), but for some reason it doesn't work.

Thanks

Upvotes: 0

Views: 52

Answers (3)

Srle
Srle

Reputation: 10496

When you declare variable with "no var" you will "accidentally" create global variable (attached to window object) so rule of thumb: Always use "var" with variable declaration. With "var" here, you will create local variable to setup function.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816322

Because in this situation, property = 'hello!' is the same as window.property = 'hello!', not this.property = 'hello!'.

If you assign to an undeclared variable, it will create a global variable.

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

When JavaScript finds a loose assignment like property = 'hello!', it will create a global variable (or raise an error, if in strict mode). So if you want it to be a property, you have to be explicit.

Upvotes: 2

Related Questions