新手提醒。我是JavaScript的新手。喜欢它到目前为止。我有一点问题,希望有人可以帮助我:
这是我在.js文件中的脚本:
function human(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
this.yearsToRetirement = function(){
return 65 - this.age;
};
}
var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement);
但这是我的浏览器输出:
Steve 34 Malefunction (){ return 65 - this.age; }
正如您可能已经猜到的那样,我正在寻找一个" 31"我们在哪里看到function (){ return 65 - this.age; }
......什么给出了?
非常感谢任何帮助。
答案 0 :(得分:1)
由于yearsToRetirement是您想要执行的功能。试试这个
var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement());
答案 1 :(得分:0)
您可以通过getter
完成此操作。然后,Steve.yearsToRetirement
工作正常。
function human(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
var _yearsToRetirement = 65 - this.age;
Object.defineProperties(this, {
yearsToRetirement: {
get: function () {
return 65 - this.age;
},
enumerable: true
}
});
}
var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement + "<br>");
Steve.age = 40;
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement);
答案 2 :(得分:0)
您在此处获取yearsToRetirement
作为功能对象而未运行它:
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement);
相反,您需要调用该函数,如下所示:
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement());