【问题标题】:Accessing methods from function constructors从函数构造函数访问方法
【发布时间】:2018-09-25 07:48:19
【问题描述】:

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

【问题讨论】:

标签: javascript instance


【解决方案1】:

您可以简单地在构造函数内的retirementAge 方法中调用它

this.retirementAge = function() {
   console.log(66 - this.calculateAge())
}

并像使用它

john.retirementAge();

【讨论】:

  • calculateAge() 不返回值。
【解决方案2】:

如果您让calculateAge 方法返回一个值,您将能够在retirementAge 方法中访问它。 试试这个:

this.calculateAge = function () {
    return 2018 - this.yearOfBirth
  }
  this.retirementAge = function () {
    return 66 - this.calculateAge()
  }
}

【讨论】:

    【解决方案3】:

    您可以创建返回值的方法,然后在获取值的方法中使用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());

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2022-01-07
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多