-2

Consider the following code

var obj = {
    "vala" : function(arg){...}
    "valb" : obj.vala    // because the function to assign here is same in code.
}

I cannot create function outside of obj object.
I tried "valb" : this.vala but it didn't work.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
afzalex
  • 8,598
  • 2
  • 34
  • 61
  • 1
    I don't see any JSON here. – Hacketo Sep 09 '15 at 08:11
  • JavaScript objects are not JSON. You can't read a property of a JavaScript object from a variable before you've created the object and assigned it to that variable. – Quentin Sep 09 '15 at 08:13

2 Answers2

1

You can't reference an object during initialization when using object literal syntax. You need to reference the object after it is created.

or you can create a constructor function

var settings = new function() {
    this.user = "someuser";
    this.password = "password";
    this.country = "Country";
    this.birthplace = this.country;
};
Mr Megamind
  • 381
  • 2
  • 7
0

You cannot access vala during initialisation like that. But you can add valb after obj is created:

var obj = {
  "vala" : function(arg){ console.log(arg); }       
}

obj["valb"] = obj.vala;

console.log(obj.vala(1));
console.log(obj.valb(2));
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91