Recently I tried to create an object using object literal. And I need a property that use another property in the object. Like this
var object = {
property1:'property1',
property2:'property2 is from ' + this.property1
};
console.log(object.property2);// property2 is from undefined
The this.property1
is undefined
in the property2
.
I do know many ways to deal with this problem. My question is what happens behind the scenes? In other words, how javascript engine interpret object literal? I know "hoisting" happens in the function. Does "hoisting" happens in object literal?
Thanks.
That's what happens:
this
refers to the scope where your code is running.
The same way in this code:
var a = 42;
var o = {
key: a
};
a
is resolved from the current scope, the this
reference in your code is resolved to whatever this
refers to "outside" of an object literal. (quotes with "outside"
are used since there is no any "inside" or "outside" of literal - all the code runs in the current scope).
So technically your code could be transformed to something like
var a = this;
var object = {
property1:'property1',
property2:'property2 is from ' + a.property1
};
or even
var p = this.property1;
var object = {
property1:'property1',
property2:'property2 is from ' + p
};
so that some special properties of this
did not confuse you.