Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an exist property in object [duplicate]

Tags:

javascript

I'm trying this

var a = {
    "a" : "Hey",
    "b" : this.a + "!"
};

console.log(a.b);

==>"undefined!"

but if I use this it works fine.

var a = {};
a.a = "haha";
a.b = a.a + "!";

console.log(a.b);

==>"haha!" 

How can I use the first way to make it work?

like image 826
Hero Sandwich Avatar asked Dec 12 '22 13:12

Hero Sandwich


1 Answers

this doesnt exist in that context of an Object literal. You will have to write a.a instead of this.a. However, while inside a function which is defined in the object, this actually refers to the object itself.

This has to do with JavaScripts referencing environments.

like image 192
Eric Avatar answered Dec 27 '22 19:12

Eric