Uncaught Reference Error: (function) is not defined JAVASCRIPT

Uncaught Reference Error: (function) is not defined JAVASCRIPT


const markProperties = {
    fullName: 'Mark Miller',
    mass: 78,
    height: 1.69,
        calcBMI: function () {
        return this.mass / this.height ** 2;
    },
    bmi: calcBMI()



    


}

const johnProperties = {
    fullName: 'John Smith',
    mass: 92,
    height: 1.95,

    calcBMI: function () {
        this.bmi = this.mass / this.height ** 2;
        return this.bmi;
    },
    bmi: calcBMI()
};

const checkWinner = () => {
    if (johnProperties.bmi > markProperties.bmi) {
        return "John's BMI (" + johnProperties.bmi + ") is higher than Mark's BMI (" + markProperties.bmi + ")";
    } else if (markProperties.bmi > johnProperties.bmi) {
        return "Mark's BMI (" + markProperties.bmi + ") is higher than John's BMI (" + johnProperties.bmi + ")";
    }
}
console.log(checkWinner());

这是代码,它说两个对象中的函数都没有定义。正如我所说,它带来了一个错误:错误:未捕获的引用错误:未定义 calcBMI

定义对象时,不能执行对象中定义的函数。 在你的情况下,你应该简单地为 bmi 属性 设置一个 getter 而不是:

const markProperties = {
    fullName: 'Mark Miller',
    mass: 78,
    height: 1.69,

    get bmi() {
        return this.mass / this.height ** 2;
    }
}

const johnProperties = {
    fullName: 'John Smith',
    mass: 92,
    height: 1.95,

    get bmi() {
        return this.mass / this.height ** 2;
    }
};

const checkWinner = () => {
    if (johnProperties.bmi > markProperties.bmi) {
        return "John's BMI (" + johnProperties.bmi + ") is higher than Mark's BMI (" + markProperties.bmi + ")";
    } else if (markProperties.bmi > johnProperties.bmi) {
        return "Mark's BMI (" + markProperties.bmi + ") is higher than John's BMI (" + johnProperties.bmi + ")";
    }
}
console.log(checkWinner());