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

JavaScript中对象方法定义的this属性直接访问为undefined如何解决

问题原因

你代码中的bmi属性仅在调用calcBmi()方法时才会被创建并赋值,未调用方法前对象本身不存在该属性,因此直接打印会输出undefined。另外补充一个逻辑笔误:标准BMI计算公式为体重(kg) / (身高(m)的平方),你现有代码里写的this.height * 2是错误的,后续方案都会修正该逻辑。

实现方案

方案1:对象初始化时主动触发一次计算

适合体重、身高后续不会修改的场景,创建对象后主动调用一次计算方法即可:

const john = {
    firstName: "Jhon",
    lastName: "Smith",
    weight: 92,
    height: 1.95,

    calcBmi: function() {
        this.bmi = this.weight / (this.height ** 2);
        return this.bmi;
    }
}
// 初始化时调用一次,后续可直接使用bmi属性
john.calcBmi();
console.log(john.bmi); // 正常输出计算结果

方案2:用getter实现自动缓存计算

适合需要多次调用、且体重身高可能后续修改的场景,访问bmi属性时自动判断是否需要重新计算,无需手动调用方法:

const john = {
    firstName: "Jhon",
    lastName: "Smith",
    weight: 92,
    height: 1.95,
    // 存储BMI计算缓存,避免重复计算
    _cachedBmi: null,

    get bmi() {
        if (this._cachedBmi) return this._cachedBmi;
        this._cachedBmi = this.weight / (this.height ** 2);
        return this._cachedBmi;
    },

    // 修改体重/身高时重置缓存,触发下次重新计算
    updateWeight(newWeight) {
        this.weight = newWeight;
        this._cachedBmi = null;
    },
    updateHeight(newHeight) {
        this.height = newHeight;
        this._cachedBmi = null;
    }
}

console.log(john.bmi); // 第一次访问自动计算
console.log(john.bmi); // 第二次访问直接返回缓存结果
john.updateWeight(88);
console.log(john.bmi); // 修改体重后自动重新计算

方案3:用Class实现可复用的结构

如果需要创建多个人物实例,用类的写法复用性更高,修改体重身高时会自动重置BMI缓存:

class Person {
    constructor(firstName, lastName, weight, height) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.weight = weight;
        this.height = height;
        this._cachedBmi = null;
    }

    get bmi() {
        if (this._cachedBmi) return this._cachedBmi;
        this._cachedBmi = this.weight / (this.height ** 2);
        return this._cachedBmi;
    }

    set weight(value) {
        this._weight = value;
        this._cachedBmi = null;
    }
    get weight() {
        return this._weight;
    }

    set height(value) {
        this._height = value;
        this._cachedBmi = null;
    }
    get height() {
        return this._height;
    }
}

const john = new Person("John", "Smith", 92, 1.95);
console.log(john.bmi); // 直接访问属性即可获取结果
john.weight = 85;
console.log(john.bmi); // 修改属性后自动重新计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:07