JavaScript继承原型
如果我们在每个子函数中使用此方法调用构造函数,那么当我们可以直接继承父属性时,为什么需要为继承设置prototype对象JavaScript继承原型,javascript,inheritance,Javascript,Inheritance,如果我们在每个子函数中使用此方法调用构造函数,那么当我们可以直接继承父属性时,为什么需要为继承设置prototype对象 function Employee() { this.name = ""; this.dept = "general"; } function Manager() { Employee.call(this); this.reports = []; } Manager.prototype = Object.create(Employee.prototype);
function Employee() {
this.name = "";
this.dept = "general";
}
function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
我们可以使用继承,即使我们没有将
Manager
的原型设置为Employee
,通常原型用于在其上放置函数/方法,而不是属性,因为使用属性,您将在所有对象实例之间共享一个属性值。此外,如果在构造函数中添加方法,则可能不需要为继承设置原型。例如:
function Employee(name) {
this.name = "";
this.dept = "general";
this.reportName = function() {return this.name};
}
function Manager(name) {
Employee.call(this, name);
this.reports = [];
}
var manager = new Manager('Peter');
manager.reportName(); // Peter
然而,在对象的构造函数中添加方法/函数是低效的,因为每次调用构造函数时都会创建函数的实例。所以通常,所有方法,而不是属性,都是在原型上分配的,如下所示:
function Employee(name) {
this.name = "";
this.dept = "general";
}
Employee.prototype.reportName = function() {return this.name};
现在,在这种情况下,仅仅调用构造函数是不够的:
function Manager(name) {
Employee.call(this, name);
this.reports = [];
}
var manager = new Manager('Peter');
manager.reportName(); // throws an error
您需要设置一个原型:
Manager.prototype = Object.create(Employee.prototype)
var manager = new Manager('Peter');
manager.reportName(); // 'Peter'
尝试不使用它的员工的newmanager()实例,或者尝试在员工的原型上添加内容。