Javascript - 输出对象方法的返回值

时间:2015-10-02 16:39:54

标签: javascript object methods return

新手提醒。我是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; }

......什么给出了?

非常感谢任何帮助。

3 个答案:

答案 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());