Search code examples
javascriptjavascript-objects

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?


Solution

  • 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