Gon*_*ack 2 javascript inheritance
我以下列方式在JavaScript中应用继承:
var employee = function(name) {
this.name = name;
}
employee.prototype.getName = function() {
return this.name;
}
var pEmployee = function(salary) {
this.salary = salary;
}
pEmployee.prototype.getSalary = function() {
return this.salary;
}
var employee = new employee("mark");
pEmployee.prototype = employee;
var pe = new pEmployee(5000);
console.log(pe.getName());
console.log(pe.getSalary());Run Code Online (Sandbox Code Playgroud)
但它在控制台中显示以下错误:
未捕获的TypeError:pe.getSalary不是函数
谁能告诉我这个错误背后的原因是什么?
这是因为你已经添加getSalary到对象pEmployee.prototype引用,但随后完全被 pEmployee.prototype新对象替换.所以新对象自然没有getSalary.
您所展示的不是在ES5及更早版本中设置继承的正确方法.相反,请参阅内联注释:
var Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function() {
return this.name;
};
var PEmployee = function(name, salary) {
// Note call to superclass
Employee.call(this, name);
// Now this level's initialization
this.salary = salary;
};
// This sets up inheritance between PEmployee.prototype and
// Employee prototype (then fixes up the
// constructor property)
PEmployee.prototype = Object.create(Employee.prototype);
PEmployee.prototype.constructor = PEmployee;
// NOW you add the method
PEmployee.prototype.getSalary = function() {
return this.salary;
};
// Usage
var employee = new Employee();
var pe = new PEmployee("Mark", 5000);
console.log(pe.getName());
console.log(pe.getSalary());Run Code Online (Sandbox Code Playgroud)
请参阅我的答案,以获得更全面的示例,以及使用ES2015 class语法时的样子.