我不确定为什么这不起作用..
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));
答案 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());