function father() { this.faName = 'father'; this.names=['11','22'] } father.prototype.getfaName = function() { console.log(this.faName); }; function child() { this.chName = 'child'; } child.prototype = new father(); child.prototype.constructor = child; child.prototype.getchName = function() { console.log(this.chName); }; var c1=new child(); c1.names.push("sasa"); var c2=new child(); console.log(c2.names) //原型上的names属性被共享了 不是咱们所须要的
这种继承会有以下的缺点:
一、若是父类包含有引用类型的属性 全部的子类就会共享这个属性。
二、在建立子类的实例时 不能向父类的构造函数传递参数es6
原型继承+构造函数的继承app
function father(name) { this.faName = 'father'; } father.prototype.getfaName = function() { console.log(this.faName); }; function child(args) { this.chName = 'child'; father.apply(this,[]); //第二次调用父类构造函数 } child.prototype = new father(); //第一次调用父类构造函数 child.prototype.constructor = child; child.prototype.getchName = function() { console.log(this.chName); };
子类继承父类的属性,一组在子类实例上,一组在子类原型上(在子类原型上建立没必要要的多余的属性)函数
function father(name) { this.faName = 'father'; } father.prototype.getfaName = function() { console.log(this.faName); }; function object(o) { //建立一个原型为o的新对象 function F() {}; F.prototype = o; return new F(); } /** * 通用方法实现子类继承父类 * @param {function} child 子类构造函数 * @param {function} father 被继承的父类构造函数 */ function inheritPrototype(child, father) { var prototype = object(father.prototype); //建立一个指定原型的对象 prototype.constructor = child; //加强对象 child.prototype = prototype; //子类的原型等于该对象 } function child(args) { this.chName = 'child'; father.apply(this,[]); //调用父类的构造函数能够经过args传递参数 } inheritPrototype(child, father); //子类的原型等于new 空函数(), 而new 空函数()出来的对象的原型等于父类的原型 child.prototype.getchName = function() { console.log(this.chName); }; console.log( child.prototype.isPrototypeOf(new child()) ); //true console.log(new child() instanceof child); //true
优势:1.只调用一次父类的构造函数,避免了在子类原型上建立没必要要的,多余的属性this
2.原型链保持不变
class father{ constructor(name){ this.name=name this.names=[1,2,3] } getname(){ console.log(this.name); } } class child extends father{ constructor(name){ super(name); } sayHello(){ console.log("sayHello"); } static hh(){ console.log("hh") } } var cc=new child("juanjuan"); cc.sayHello(); cc.getname(); //juanjuan child.hh(); //hh cc.names.push("wqwq"); var c1=new child("sasasa"); console.log(c1.names) //[1,2,3]