<script type="text/javascript"> //类的声明 function Animal() { this.name = 'name' } // es6中的class的声明 class Animal2 { constructor() { this.name = name } } </script>
console.log(new Animal(), new Animal2());
/** * 借助构造函数实现继承 */ function Parent1() { this.name = 'parent1' } function Child1() { Parent1.call(this); this.type = 'child1'; } console.log(new Child1());
function Parent1() { this.name = 'parent1' } Parent1.prototype.say = function(){};
function Child1() { Parent1.call(this); this.type = 'child1'; } console.log(new Child1());
/** * 借助原型链实现即成 */ function Parent2() { this.name = "parent2"; } function Child2() { this.type = "child2" } Child2.prototype = new Parent2(); console.log(new Child2());
/** * 借助原型链实现即成 */ function Parent2() { this.name = "parent2"; this.play = [1,2,3] } function Child2() { this.type = "child2" } Child2.prototype = new Parent2(); var s1 = new Child2(); var s2 = new Child2(); s1.play.push(4); console.log(s1.play,s2.play);
/** * 组合方式(结合构造函数 和 原型链的优点) */ function Parent3 () { this.name = 'parent3'; } function Child3 () { Parent3.call(this); this.type = 'child3' } Child3.prototype = new Parent3();
我们再加上方法,看看是否能避免上面的问题呢
/** * 组合方式(结合构造函数 和 原型链的优点) */ function Parent3 () { this.name = 'parent3'; this.play = [1,2,3]; } function Child3 () { Parent3.call(this); this.type = 'child3' }
Child3.prototype = new Parent3(); var s3 = new Child3(); var s4 = new Child3(); s3.play.push(4); console.log(s3.play,s4.play);
这个时候发现就不一样了,避免了eg2的缺点,这种组合方式结合了优点,弥补了缺点,这是通常实现继承的方式
4)
/** * 组合继承的优化 */ function Parent4 () { this.name = 'parent4'; this.play = [1,2,3]; } function Child4 () { Parent4.call(this); this.type = 'child4' } Child4.prototype = Parent4.prototype; var s5 = new Child4(); var s6 = new Child4();
这样父类的原型链只执行了一次,但是还剩下一个问题,s5,s6都是父类的实例,没有自己的实例,prototype里面有个contron指明是哪个的实例,而子类的prototype拿的直接是父类的prototype,所以当然拿的是父类的构造函数
/** * 组合继承的优化2 */ function Parent5 () { this.name = 'parent5'; this.play = [1,2,3]; } function Child5 () { Parent5.call(this); this.type = 'child5' } Child5.prototype = Object.create(Parent5.prototype); Child5.prototype.constructor = Child5;
Object.create方法创建原型对象,Parent5.prototype就是create方法的一个参数,一层一层往上找实现了继承,同时完成了继承,这个就是实现继承的完美方式