2017-03-31 19 views
1

我需要一些幫助這個代碼。它返回一個字符串,而不是所需的結果,我有點卡住了。Javascript的年齡計算器不工作,它返回一個字符串

function calculateAge(name, birthYear) { 
    this.name = name; 
    this.birthYear = birthYear; 
    this.result = function(){ 
     var currentYear = new Date().getFullYear(); 
     return currentYear - birthYear; 
    }; 
    document.write("Hi there " + this.name + " ." + "You are " + this.result + " old !"); 
}; 

var John = new calculateAge("ion" , 1980); 
John.result(); 

回答

1

調用函數以獲得所需的結果 - this.result()

function calculateAge(name, birthYear) { 
 

 
    this.name = name; 
 
    this.birthYear = birthYear; 
 
    this.result = function() { 
 
    var currentYear = new Date().getFullYear(); 
 
    return currentYear - birthYear; 
 
    }; 
 
    document.write("Hi there " + this.name + " ." + "You are " + this.result() + " old !"); 
 
}; 
 
var John = new calculateAge("ion", 1980); 
 
John.result();

+0

謝謝你,善良的用戶! :) –

+0

@CautisMarius接受我的回答(: –