这就是问题所在:
var Employee = new function(name)
// ------------^^^
{
this.name=name;
}
(PermanenetEmployee 也是如此。)
你不想在那里new。 new 调用函数。您想稍后再执行此操作,就像分配给 employee 时一样。
请注意,您在它们之间设置继承的方式是一种反模式。要使PermanenetEmployee 正确“子类化”Employee,请执行以下操作:
PermanenetEmployee.prototype = Object.create(Employee.prototype);
PermanenetEmployee.prototype.constructor = PermanenetEmployee;
不是
var employee = new Employee("rahul");
PermanenetEmployee.prototype = employee;
...然后让PermanenetEmployee 接受name 并将其传递给Employee:
var PermanenetEmployee = function(name, annualsalary) {
Employee.all(this, name); // <====
// ...
};
...或者更好地使用,使用 ES2015 ("ES6") class (如果需要,可以进行转换,例如使用 Babel)。
这是正确的设置。我还修正了PermanenetEmployee 中的错字:
var Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function() {
return this.name;
};
var PermanentEmployee = function(name, annualSalary) {
Employee.call(this, name);
this.annualSalary = annualSalary;
};
// Set up subclass
PermanentEmployee.prototype = Object.create(Employee.prototype);
PermanentEmployee.prototype.constructor = PermanentEmployee.prototype;
PermanentEmployee.prototype.getAnnualSalary = function() {
return this.annualSalary;
};
// Using
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
在 ES2015 中:
class Employee {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class PermanentEmployee extends Employee {
constructor(name, annualSalary) {
super(name);
this.annualSalary = annualSalary;
}
getAnnualSalary() {
return this.annualSalary;
}
}
// Using
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
再次注意,如果您想在野外使用该语法(目前),则需要进行转译。