[JS]继承方式总结

方式一:原型链继承(prototype模式)

  1. function Animal(){
  2. this.species = "动物";
  3. }
  4. function Cat(name,color){
  5. this.name = name;
  6. this.color = color;
  7. }
  8. Cat.prototype = new Animal();//核心
  9. Cat.prototype.constructor = Cat;

缺点:
1.原型上的引用类型的属性和方法被所有实例共享(个人觉得这不应该算缺点,毕竟原型就是派这个用处的)
2.创建Cat的实例时,无法向Animal传参

方式二:经典继承(构造函数绑定)

  1. function Animal(){
  2. this.species = "动物";
  3. }
  4. function Cat(name,color){
  5. Animal.call(this);//核心,或Animal.apply(this,arguments);
  6. this.name = name;
  7. this.color = color;
  8. }

优点:
1.避免了引用类型的属性和方法被所有实例共享,因为根本没用到原型嘛
2.创建Cat的实例时,可以向Animal传参

缺点:
1.属性和方法都在构造函数中定义,每次创建实例都会创建一遍属性和方法

方式三:组合继承(原型链继承和经典继承双剑合璧)

  1. function Parent (name) {
  2. this.name = name;
  3. this.colors = ['red', 'blue', 'green'];
  4. }
  5. Parent.prototype.getName = function () {
  6. console.log(this.name)
  7. }
  8. function Child (name, age) {
  9. Parent.call(this, name);//核心
  10. this.age = age;
  11. }
  12. Child.prototype = new Parent();//核心
  13. var child1 = new Child('kevin', '18');
  14. child1.colors.push('black');
  15. console.log(child1.name); // kevin
  16. console.log(child1.age); // 18
  17. console.log(child1.colors); // ["red", "blue", "green", "black"]
  18. var child2 = new Child('daisy', '20');
  19. console.log(child2.name); // daisy
  20. console.log(child2.age); // 20
  21. console.log(child2.colors); // ["red", "blue", "green"]

优点:
1.融合原型链继承和构造函数的优点融合原型链继承和构造函数的优点

缺点:
1.两次调用Parent构造函数,在Child.prototype上增加了额外、不需要的属性,还破坏了原型链

方式四:寄生组合继承

  1. function Parent (name) {
  2. this.name = name;
  3. this.colors = ['red', 'blue', 'green'];
  4. }
  5. Parent.prototype.getName = function () {
  6. console.log(this.name)
  7. }
  8. function Child (name, age) {
  9. Parent.call(this, name);//核心
  10. this.age = age;
  11. }
  12. Child.prototype = Object.create(Parent.prototype);//核心
  13. Child.prototype.constructor = Child;
  14. var child1 = new Child('kevin', '18');
  15. console.log(child1)

优点:在组合继承的基础上,避免了在 Child.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf

参考链接:
https://github.com/mqyqingfeng/Blog/issues/16
http://www.ayqy.net/blog/%E9%87%8D%E6%96%B0%E7%90%86%E8%A7%A3js%E7%9A%846%E7%A7%8D%E7%BB%A7%E6%89%BF%E6%96%B9%E5%BC%8F/
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html

posted @ 2017-05-30 21:09  enginex  阅读(144)  评论(0编辑  收藏  举报