我不确定为什么这不起作用..
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));
最佳答案
它不起作用,因为您实际上从未创建过 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());
关于javascript - 非常基本的对象原型(prototype)不知道为什么不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924778/