You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ES5环境下对象内garages['1']引用this.cars为何返回undefined?

问题解答

为什么garages['1']的值是undefined?

不是因为cars未初始化,核心原因是对象字面量创建过程中,this并不指向正在构建的person对象。

在ES5的全局环境下,你写的{ 1: this.cars }里的this,指向的是全局对象(浏览器环境为window,Node.js环境为global),而全局对象中并没有cars属性,所以结果自然是undefined。哪怕cars和garages写在同一个对象字面量里,此时person对象还未完全创建完成,无法通过this访问到它的内部属性。

修复方案

方案1:创建对象后单独赋值garages

var person = {
  cars: ["Ford", "Mercedes", "S Coupe"]
};
person.garages = { 1: person.cars };

console.log(person);
// 输出:
// {
//   cars: [ 'Ford', 'Mercedes', 'S Coupe' ],
//   garages: { '1': [ 'Ford', 'Mercedes', 'S Coupe' ] }
// }

方案2:使用构造函数(ES5常用写法)

function Person() {
  this.cars = ["Ford", "Mercedes", "S Coupe"];
  this.garages = { 1: this.cars };
}

var person = new Person();
console.log(person);

方案3:使用getter函数(ES5支持)

var person = {
  cars: ["Ford", "Mercedes", "S Coupe"],
  get garages() {
    return { 1: this.cars };
  }
};

console.log(person.garages);
// 输出:{ '1': [ 'Ford', 'Mercedes', 'S Coupe' ] }

内容的提问来源于stack exchange,提问作者ati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:20:19