继承 -- 借用构造函数

Apr 30, 2019 5:06·159 words ·1 minutes read

function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {
    // 继承了 SuperType
    // 没有调用 new
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.colors.push("black);
alert(instance1.colors);    // "red, blue, green, black"

var instance2 = new SubType();
alert(instance2.colors);    // "red, blue, green"

避免了使用原型链继承时,引用类型属性被所有实例共享的问题

  • 其他优点

    • 可以传递参数

      function SuperType(name) {
        this.name = name;
      }
      function SubType(){
        // 继承了 SuperType,同时还传递了参数
        SuperType.call(this, "Nicholas");
      
        // 实例属性
        this.age = 29;
      }
      
  • 借用构造函数的问题

    • 方法都在构造函数中定义,因此函数复用就无从谈起了