本文共 1946 字,大约阅读时间需要 6 分钟。
继承是类与类之间的关系,其主要作用是使子类能够继承父类的属性和方法。通过继承,可以在子类中重复使用父类的功能,避免代码冗余。
继承的实现方式主要有四种:原型链继承、借用构造函数继承、组合继承以及原型式继承。每种方法都有其独特的特点和适用场景。
原型链继承的核心思想是让新实例的原型等于父类的实例。这种方法通过重新赋值 prototype 属性来实现继承。
function Human(name) { this.name = name; this.eat = function() { console.log('吃饭'); };}Human.prototype.run = function() { console.log('我很能跑');};// 实现继承function Man(age) { this.age = age;}Man.prototype = new Human('小王');// 创建实例let man = new Man('11');console.log(man.age); // 11console.log(man.name); // '小王'man.run(); // '我很能跑'let man2 = new Man('33');console.log(man2.age); // 33console.log(man2.name); // '小王'man2.run(); // '我很能跑' 优点:
缺点:
借用构造函数继承通过调用 call 和 apply 方法,将父类的构造函数引入子类,从而实现继承。
function Man(name, age) { Human.call(this, name); this.age = age;}// 创建实例let man1 = new Man('小王', 12);console.log(man1.name); // '小王'console.log(man1.age); // 12man1.eat(); // '吃饭'let man2 = new Man('大王', 21);console.log(man2.name); // '大王'console.log(man2.age); // 21 优点:
缺点:
组合继承结合了原型链继承和借用构造函数继承的优点,既能传递参数,又能继承原型链上的属性。
function Man(name, age) { Human.call(this, name); this.age = age;}Man.prototype = new Human();// 创建实例let man1 = new Man('小王', 12);console.log(man1.name); // '小王'console.log(man1.age); // 12man1.eat(); // '吃饭'man1.run(); // '我很能跑'let man2 = new Man('大王', 21);console.log(man2.name); // '大王'console.log(man2.age); // 21man2.run(); // '我很能跑' 优点:
缺点:
原型式继承通过创建一个函数来包装对象,然后返回新对象,使其继承原型链上的属性。
function Man(obj) { function F() {} F.prototype = obj; return new F();}// 创建实例let human = new Human('小');let man = Man(human);console.log(man.name); // '小' 优点:
缺点:
如果你对前端技术感兴趣,可以加入我们的交流群,和技术大牛一起探讨更多有趣的内容!
转载地址:http://ktri.baihongyu.com/