"undefined!" ...">

How to use the exist property in an object

I'm trying to do it

var a = { "a" : "Hey", "b" : this.a + "!" }; console.log(ab); ==>"undefined!" 

but if i use this it works fine.

 var a = {}; aa = "haha"; ab = aa + "!"; console.log(ab); ==>"haha!" 

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

+4
source share
3 answers

this does not exist in this context of the object literal. You need to write aa instead of this.a However, while inside the function defined in the object, this actually refers to the object itself.

This applies to JavaScripts referenced environments.

+6
source

You can not.

Here's how to literally declare an object in JavaScript; no self-references will work

All references to this resolved based on the area in which the code is executed, by default window , if you are in the global area.

Update

Without resorting to the new syntax getters and seters, you can do two things:

  • Create an object, but do not consider properties that contain references to yourself; then add them. This is what you did.

  • Instead, turn the property into a function:

     var a = { "a" : "Hey", "b" : function() { return this.a + "!"; } }; console.log(ab()); // "Hey!" 

Be careful with this approach, as changing the value of aa will also affect the output of ab() .

+5
source

The edition of Ekmascript 5 presents some nice addition to the objects: Setters and getters. In modern browsers, you can use the getter method to achieve the desired result:

 var a = { "a" : "Hey", get b(){ return this.a + "!" }, set c(x){ this.a = x} }; 

Now ab will give you the correct Hey! result Hey! .

The setter function for c will make the normal assignment ac = "foo" really set aa to foo !

+2
source

Source: https://habr.com/ru/post/1489226/


All Articles