【问题标题】:JavaScript Inheritance prototypicalJavaScript 继承原型
【发布时间】:2016-11-14 05:40:01
【问题描述】:

如果我们在每个子函数中使用this调用构造函数方法,可以直接继承父属性,为什么还要设置原型对象进行继承?

function Employee() {
  this.name = "";
  this.dept = "general";
}

function Manager() {
  Employee.call(this);
  this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);

即使我们不将Manager的原型设置为Employee,我们也可以使用继承。

【问题讨论】:

  • 试试new Manager() instanceof Employee 没有它,或者尝试在Employee 的原型上添加东西。

标签: javascript inheritance


【解决方案1】:

通常原型用于在其上放置函数/方法,而不是属性,因为通过属性,您将在所有对象实例之间共享一个属性值。此外,如果在构造函数中添加方法,则可能不需要为继承设置原型。例如:

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'

【讨论】:

    猜你喜欢
    • 2010-09-28
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多