[英]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.