繁体   English   中英

从函数构造函数访问方法

[英]Accessing methods from function constructors

设计人员如何在同一个Person函数构造函数中访问retireAge方法的值? 在此处输入图片说明

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

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

并像这样使用

john.retirementAge();

如果使您的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()); 

暂无
暂无

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

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