简体   繁体   中英

Why does error occur at var obj={'A':'B','C':obj['A']};?

I want to create an javascript object, which value of "C" copies value of "A" :

 var obj={ 'A':'some complex function returns a string', 'C':obj['A'] }; 

But it has errors. I try to check if key 'A' really created:

 var f=function(str){ console.log(str); return str; }; var obj={ [f('A')]:[f('B')], "C":obj['A'] }; 

which prints

B
A

and then errors. Which means 'A' created but it still says obj['A'] is not defined. Why would that happen?

Your current attempt obviously fails because by the time the code constructs new object the value of obj variable was not assigned yet.

You could check it by using

var obj = { C: typeof obj}

I want to create an javascript object, which value of "C" copies value of "A"

If you want C to always reflect the value of A you could use

var obj = {
  A: 'Some value',
  get C() {
    return this.A;
  }
}

Or split obj declaration

var obj = { A: 'Some Value' };
obj.C = obj.A

You get the error because obj was not yet defined when you attempted to acces it from inside of it.

To make your code work you could use a getter.

The get syntax binds an object property to a function that will be called when that property is looked up. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Also you do not need quotes for your object properties.

Quotes can be omitted if the property name is a numeric literal or a valid identifier name.

 var obj = { A : 'Hello', get C() { return this.A; } }; console.log(obj.C); 

You can not reference a variable that has not created yet. You can do it like this.

var obj = { 'A' : 'some complex function returns a string' }
obj['C'] = obj['A'] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM