1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 function Parent ( ) { this .sayHello = function ( ) { console .log ("Hello" ); } } Parent .prototype .a = "我是父类prototype上的属性" ;function Child ( ) { Parent .call (this ) } Child .prototype = Object .create (Parent .prototype );Child .prototype .constructor = Child ;var child1 = new Child ();var child2 = new Child ();console .log (child1.sayHello === child2.sayHello );var parentObj = new Parent ();console .log (parentObj.a );console .log (child1.a )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 function Parent ( ) { this .sayHello = function ( ) { console .log ("Hello" ); } } Parent .prototype .a = "我是父类prototype上的属性" ;function Child ( ) { Parent .call (this ) } Child .prototype .childFunction = ()=> { console .log ("我是child方法" ); } Child .prototype = Object .create (Parent .prototype );Child .prototype .constructor = Child ;var child1 = new Child ();child1.childFunction ();
优点: 1 ,原型属性不会被共享 2 ,可以继承父类的原型链上的属性和方法 3 .只调用了 1 次 Parent(), 因此,它不会在 Child 的prototype 上添加 Parent 的属性和方法。 缺点: Child.prototype的原始属性和方法会丢失。