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/