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

very basic object prototype not sure why isn't working

本文关键字:工作 为什么 不确定 对象 原型 非常      更新时间:2023-09-26

我不知道为什么这不起作用。。

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