segmentfault官方|ES5 继承( 二 )


functionSuperType{
this.colors = [ "red", "blue", "green"];
}
functionSubType{
// 继承SuperType
SuperType.call(this);
}
letinstance1 = new SubType;
instance1.colors.push( "black");
console.log(instance1.colors);
// "red,blue,green,black";
letinstance2 = new SubType;
console.log(instance2.colors);
// "red,blue,green";
instance1 instance2两个实例就不会相互影响 。

  • 可以为父类构造函数传参
functionSuperType(name) {
this.name = name;
}
functionSubType(name) {
// 继承SuperType并传参
SuperType.call(this, name);
// 实例属性
this.age = 29;
}
letinstance = new SubType( "geek");
console.log(instance.name); // "geek";
console.log(instance.age); // 29
动态传递参数到父类构造函数
劣势:
  • 定义在父类prototype上的方法 , 子类无法继承
functionSuperType(name) {
this.name = name;
}
SuperType.prototype.say = function{
console.info( "hello");
};
functionSubType(name) {
// 继承SuperType并传参
SuperType.call(this, name);
// 实例属性
this.age = 29;
}
letinstance = new SubType( "geek");
console.log(instance.name); // "geek";
console.log(instance.age); // 29
instance.say // 获取不到该函数
通过 new 实例化后 , 实例才能拿到prototype上的方法 , a.__proto__===Animal.prototype , 所以instance.say不存在
  • 定义在父类构造函数中方法无法共享
每次实例化子类 , 都会调用父类构造函数 , 其内部定义的方法都是新的 , 占用了不必要的内存 , 没有实现方法的共享 。
组合继承
组合继承兼顾原型链继承跟盗用构造函数的优点 , 这样既可以把方法定义在原型上以实现重用 , 又可以看让每个实力都有自己的属性 。
functionSuperType(name) {
this.name = name;
this.colors = [ "red", "blue", "green"];
}
SuperType.prototype.sayName = function{
console.log(this.name);
};
functionSubType(name, age) {
// 继承属性 , 绑定上下文为SubType的实例
SuperType.call(this, name);
this.age = age;
}
// 继承方法
SubType.prototype = new SuperType;
SubType.prototype.sayAge = function{
console.log(this.age);
};
letinstance1 = new SubType( "Nicholas", 29);
instance1.colors.push( "black");
console.log(instance1.colors);
// "red,blue,green,black"
instance1.sayName; // "Nicholas";
instance1.sayAge; // 29
letinstance2 = new SubType( "Greg", 27);
console.log(instance2.colors);
// "red,blue,green";
instance2.sayName; // "Greg";
instance2.sayAge; // 27
  • 可以传递参数到父类构造函数
  • 两个实例中的引用类型不会相互影响
  • 实例可以调用父类的方法 , 且实现方法的共享
劣势:
SuperType会被调用两次 , SubType实例跟原型链上都有name跟colors属性 。
原型式继承
不定义构造函数通过原型实现对象之前的继承 。
functionobject(o) {


推荐阅读