retireingAge方法如何访问同一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());
答案 0 :(得分:4)
如果要通过调用获取值,则需要从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())
答案 1 :(得分:0)
它可以访问它,您只需忘记括号并返回值即可。
var 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(john.retirementAge(john.calculateAge()))