简体   繁体   中英

JavaScript Variable Assignment in an 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);

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();

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