简体   繁体   English

从函数构造函数访问方法

[英]Accessing methods from function constructors

How can the retirementAge method access the value of calculateAge method in the same Person function constructor? 设计人员如何在同一个Person函数构造函数中访问retireAge方法的值? 在此处输入图片说明

You could simply call it within the retirementAge method inside the constructor function 您可以在构造函数内部的retirementAge方法中简单地调用它

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

and use it like 并像这样使用

john.retirementAge();

If you make your calculateAge method return a value, you will be able to access it in the retirementAge method. 如果使您的calculateAge方法返回一个值,则可以在retirementAge方法中访问它。 Try this: 尝试这个:

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

You could make the methods to retun a value and then use this.calculateAge() in the method for getting the value. 您可以使方法重新调整值,然后在方法中使用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()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM