继承概念:
继承就是让一个类拥有另一个类的属性和方法
继承方式
方式一:
通过原型继承,给需要继承的对象换原型
function Fun(){
this.music="唱";
this.run="跳";
this.firend=function(){
console.log("giao");
}
}
function Fn(){
this.name="鸡你太美";
}
//让Fn类的原型赋值为Fun实例化的对象(new 出来的那个对象) 给Fn原型赋值
Fn.prototype=new Fun();
var fn=new Fn();
console.log(fn);//fn对象就继承了Fun类的属性和方法
此时fn的constructor属性指向的构造函数是Fun,可以手动设置回去
fn.constructor=Fn;
方式二
使用上下文调用模式(借用函数继承)
function Fun(){
this.music="唱";
this.run="跳";
this.firend=function(){
console.log("giao");
}
}
function Fn(){
this.name="鸡你太美";
Fun.call(this);//改变Fun中的this指向,并立即执行
//Fun.apply(this) 改变Fun中的this指向,并立即执行
//Fun.bind(this)()//改变Fun中的this指向,并返回新函数
}
缺点:
如果继承的这个类中的属性和方法绑定在原型上,那么这种继承方式不能继承原型上的方法和属性
方式三:
组合继承(原型继承+上下文调用)
function Fun(){
this.music="唱";
this.run="跳";
this.firend=function(){
console.log("giao");
}
}
function Fn(){
this.name="鸡你太美";
Fun.call(this);//改变Fun中的this指向,并立即执行
//Fun.apply(this) 改变Fun中的this指向,并立即执行
//Fun.bind(this)()//改变Fun中的this指向,并返回新函数
}
Fn.prototype=new Fun();
//如果只需要Fun上的原型对象的方法或属性,并且Fun没啥用了,可以直接把Fun的原型赋值给Fn,即
//Fn.prototype=Fun.prototype;
Fn.prototype.constructor=Fn;//将Fn原型的构造函数改回Fn
方式四:
class类继承
class Fun{
//定义对象的属性都在constructor方法中
constructor(){
this.music="唱";
this.run="跳";
}
//方法
friend(){
console.log("鸡你太美");
}
}
class Fn extends Fun{//使用extends关键字继承
constructor(){
// 如果父类有constructor,子类这里必须调用super()这个方法
super();//这里其实是在执行父类的constructor()方法
this.name="giao";
}
}
方式五:
在子类中调用父类继承
function Fun(){
this.music="唱";
this.run="跳";
this.firend=function(){
console.log("giao");
}
}
function Fn(){
this.name="鸡你太美";
//调用父类
this.fun=Fun;
this.fun();
}
console.log(new Fn());