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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With