一.原型链继承(prototype)
就是把要继承的办法写在原型链上
function Parent() { this.name = 'parent1'; this.play = [1, 2, 3] } function Child() { this.type = 'child2'; } Child.prototype = new Parent();
毛病:实例化的对象共用一个内存地址
二.构造函数继承(call)
function Parent(){ this.name = 'parent1';}Parent.prototype.getName = function () { return this.name;}function Child(){ Parent.call(this); this.type = 'child'}let child = new Child();console.log(child); // 没问题console.log(child.getName()); // 会报错
然而只能继承父类的实例属性和办法,不能继承原型属性或者办法
三.组合继承(手动挂上结构器,指向本人的构造函数)
function Parent3 () { this.name = 'parent3'; this.play = [1, 2, 3];}Parent3.prototype.getName = function () { return this.name;}function Child3() {// 第二次调用 Parent3() Parent3.call(this); this.type = 'child3';}// 手动挂上结构器,指向本人的构造函数// 第一次调用 Parent3()Child3.prototype = new Parent3();Child3.prototype.constructor = Child3;var s3 = new Child3();var s4 = new Child3();s3.play.push(4);console.log(s3.play, s4.play); // 不相互影响console.log(s3.getName()); // 失常输入'parent3'console.log(s4.getName()); // 失常输入'parent3'
毛病:造成了多结构一次的性能开销