继承的目的:
让子类的实例同时也具备弗雷泽私有的属性和公共的方法
第一种:原型继承(让子类的原型=父类的实例)
function Parent(){ this.x = 100;}Parent.prototype.getX = function getX(){ return this.x}function Child(){ this.y = 200}Child.prototype = new parent; //原型继承Child.prototype.getY = function getY(){ return this.y;}let a1 = new Child;console.log(a1)
第二种继承方式:call继承,只能继承父类私有的,不能继承父类公有的
function Parent(){ this.x = 100;}Parent.prototype.getX = function getX(){ return this.x}function Child(){ //在子类构造函数中,把父类当作普通方法执行 ,没有父类实例,父类原型伤的东西就和他没关系了 // this child的实例a1 Parent.call(this) //this.x = 100 相当于强制给a1这个实例设置一个私有的属性x,属性值是100, 相当于让子类的实例继承了父类的私有属性,并且也变为了子类私有的属性‘拷贝式’ this.y = 200}Child.prototype = new parent; //原型继承Child.prototype.getY = function getY(){ return this.y;}let a1 = new Child; // new this是当前实例console.log(a1)
第三种继承:寄生组合式继承(call继承+另类原型继承),父类私有变为子类私有的,父类共有的变为子类共有的
function Parent(){ this.x = 100;}Parent.prototype.getX = function getX(){ return this.x}function Child(){ Parent.call(this) this.y = 200}Child.prototype = Object.create(Parent.prototype);Child.prototype.custructor = Child;Child.prototype = new parent; //原型继承Child.prototype.getY = function getY(){ return this.y;}let a1 = new Child; // new this是当前实例console.log(a1)
第四种:ES6类和继承
es6中创建的类,不能当作普通函数执行,只能new执行class Parent(){ construtor(){ this.x = 100 } //往原型上写方法 getX(){ return this.x }}//继承:entends Parent「类似于寄生组合式继承」//注意:继承后一定要在construtor第一行加上superclass Child entends Parent{ construtor(){ super() //类似于我们的call继承,super(10,20)相当于把Parent中的construtor执行传两个参数 this.y = 100 } //往原型上写方法 getX(){ return this.y }}let c1 = new Childconsole.log(c1)