javascript - 从函数构造函数访问方法
问题描述
在同一个 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());
解决方案
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())
推荐阅读
- javascript - 获取重复键错误,但未在集合中设置唯一属性
- date - 应用程序脚本上的区域时间和日期到谷歌表未转换为本地时间
- javascript - odataclient.query 不是 nodejs 中的函数
- python - 如何解决必须安装 CMake 才能构建以下扩展:PyCharm 中的 dlib?
- android - 我正在使用 kotlin 在 android 中使用芯片视图。我需要实现clickk功能
- python - 无法读取更大文件大小的镶木地板文件
- salesforce-communities - 双重选择确认邮件
- javascript - Select option not displaying when div is changed
- regex - 主网站中子链接的 URL 正则表达式
- google-apps-script - 限制 Google Apps 脚本中的数据是否与 Google 表格连接