javascriptthisobject-literal

How can an expression within an object literal refer to another property of the same object?


What is wrong with this code? obj.bVar is undefined here, why is that? How do I assign the value of aVar to bVar?

var obj = {
    aVar: 15,
    bVar: this.aVar // This is undefined
};

console.log(obj.aVar);
console.log(obj.bVar);


Solution

  • this, in JavaScript, refers to the current scope, which is either a function call or the global scope.

    Here, this is the global scope, that is window (apart if you're doing this in a function).

    Here's a solution :

    var obj = {
        aVar: 15
    };
    obj.bVar = obj.aVar;
    

    Another one (that may or not be relevant, depending on the context of your application) would be to use a constructor :

    function Obj(){
       this.aVar = 15;
       this.bVar = this.aVar;
    }
    var obj = new Obj();