首页 > 解决方案 > 从函数构造函数访问方法

问题描述

在同一个 Person 函数构造函数中,retireageAge 方法如何访问 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());

标签: javascript

解决方案


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())


推荐阅读