gpt4 book ai didi

javascript - 从函数构造函数访问方法

转载 作者:行者123 更新时间:2023-11-28 14:28:09 25 4
gpt4 key购买 nike

retirementAge方法如何访问同一个Person函数构造函数中的calculateAge方法的值?

var Person = function(name, job, yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.calculateAge = function() {
console.log(2018 - this.yearOfBirth)
};
this.retirementAge = function(el) {
console.log(66 - this.calculateAge)
}
}

var john = new Person('John', 'teacher', 1998);
john.retirementAge(john.calculateAge());

最佳答案

如果您想通过调用来获取值,则需要从 this.calculateAge 返回一个值。当您这样做时,您只需调用函数 this.calculateAge() 即可,它应该按预期工作:

let Person = function(name, job, yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.calculateAge = function() {
return 2018 - this.yearOfBirth
};
this.retirementAge = function(el) {
return 66 - this.calculateAge()
}
}

var john = new Person('John', 'teacher', 1998);
console.log("Age:", john.calculateAge())
console.log("Years to retirement:", john.retirementAge())

关于javascript - 从函数构造函数访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52493272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com