Javascript age calculator不工作,它返回一个字符串

时间:2017-03-31 22:32:45

标签: 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 个答案:

答案 0 :(得分: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();