[英]Adding a method to an object
我在javascript中向对象添加方法时遇到问题。 以下代码应返回一个数字,而是返回NaN。 希望你能帮忙
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = pension();
}
function pension(){
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);
您可以使用原型模型 - 使pension
成为people
的方法 :
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = this.pension(); // note the `this`
}
people.prototype.pension = function(){ // note the `prototype`
var numYears = 65 - this.age;
return numYears;
};
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft); // 37
使用prototype
您的pension
方法将继承构造函数( people
)属性(允许您使用this
关键字进行引用)。
这样做的另一个好处是,在每个new
实例化people
您都不会重新创建pension
方法的新实例/召回。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
JavaScript适用于“功能范围”,因此简而言之,你的范围是错误的。 您需要绑定“this”变量或使用prototype属性在people类上创建一个函数。
您可以将其定义为原型函数
people.prototype.pension = function() {
numYears = 65 - this.age;
return numYears;
}
如果在养老金中添加console.log()行,您将看到this
是窗口,而不是人员对象。 改变this
情况的一种方法是使用call()。
this.numYearsLeft = pension.call(this);
例:
function people(name, age) { this.name = name; this.age = age; this.numYearsLeft = pension.call(this); } function pension() { numYears = 65 - this.age; return numYears; } var andrews = new people("Andrews Green", 28); console.log(andrews.numYearsLeft);
其他选择是让它成为人原型的一部分。
function people(name, age) { this.name = name; this.age = age; this.numYearsLeft = this.pension(); } people.prototype.pension = function () { numYears = 65 - this.age; return numYears; } var andrews = new people("Andrews Green", 28); console.log(andrews.numYearsLeft);
为了调用函数,你需要put()。 console.log(andrews.numYearsLeft);
应该是console.log(andrews.numYearsLeft());
也在
function pension(){
numYears = 65 - this.age;
return numYears;
}
this.age是未定义的,因此是NaN。
(已编辑)也许试试:
function people(name, age){
var that = this;
this.name = name;
this.age = age;
this.numYearsLeft = function(){
numYears = 65 - that.age;
return numYears;
};
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.