非常基本的对象原型不确定为什么不工作

时间:2015-11-25 19:19:43

标签: javascript

我不确定为什么这不起作用..

function Employee(vacation, takenAlready) {
  this.vacation_days_per_year = vacation;
  this.vacation_days_taken = takenAlready;
}

Employee.prototype.sally = function(){return this.vacation_days_per_year - this.vacation_days_taken};

console.log(sally(20, 5));

1 个答案:

答案 0 :(得分:3)

它无法正常工作,因为您实际上从未创建过Employee个实例。你所做的就是创造一个"类"并给它一些属性,一个是名为sally的函数。

您需要使用new Employee创建对象实例,然后可以调用其sally方法。

var joe = new Employee(20, 5);
console.log(joe.sally());

虽然,我不认为你真的想要命名方法sally,但你可能想要调用该对象。这可能就是你想要的:

function Employee(vacation, takenAlready) {
  this.vacation_days_per_year = vacation;
  this.vacation_days_taken = takenAlready;
}

Employee.prototype.vacation_days_left = function(){
    return this.vacation_days_per_year - this.vacation_days_taken
};

var sally = new Employee(20, 5);
console.log(sally.vacation_days_left());