【发布时间】:2018-09-25 07:48:19
【问题描述】:
retireAge 方法如何访问同一个 Person 函数构造函数中的 calculateAge 方法的值?
【问题讨论】:
-
请将代码添加为文本,而不是图像。也请看这里:minimal reproducible example
标签: javascript instance
retireAge 方法如何访问同一个 Person 函数构造函数中的 calculateAge 方法的值?
【问题讨论】:
标签: javascript instance
您可以简单地在构造函数内的retirementAge 方法中调用它
this.retirementAge = function() {
console.log(66 - this.calculateAge())
}
并像使用它
john.retirementAge();
【讨论】:
calculateAge() 不返回值。
如果您让calculateAge 方法返回一个值,您将能够在retirementAge 方法中访问它。 试试这个:
this.calculateAge = function () {
return 2018 - this.yearOfBirth
}
this.retirementAge = function () {
return 66 - this.calculateAge()
}
}
【讨论】:
您可以创建返回值的方法,然后在获取值的方法中使用this.calculateAge()。
var Person = function(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
this.calculateAge = function() {
return 2018 - this.yearOfBirth;
};
this.retirementAge = function() {
return 66 - this.calculateAge();
}
};
var john = new Person("John", 1998, 'teacher');
console.log(john.retirementAge());
console.log(john.calculateAge());
【讨论】: