javaScript---继承

1:原型链继承
特点:
1:父类追加的属性和方法,子类可以直接使用;子类自身追加的方法和属性同样可以直接使用
2:对象原型是父类也是子类
3:(缺点)不能实现多继承;当属性是引用类型时,会共享引用类型
示例:
function animal(){
this.weight=n;
this.height=m;
this.guojia=[“中国”,“美国”]
this.eat=function(w){
return “吃”+w
}
}
function cat(){
this.color=“黄色”
this.sleep=function(){
return “躺着睡觉”
}
}
animal.prototype.sex=“母”//在new之前追加属性,animal实例化后即可看到追加的属性
cat.prototype=new animal()//animal实例化,cat继承
var c=new cat()//实例化cat
c.guojia.push(“英国”)//属性是引用类型,会共享引用类型,此时输出c和c1 拥有的方法和属性一致
var c1=new cat()//
console.log©//c拥有父类和自身以及父类追加和自身追加的属性和方法
console.log(c instanceof animal)//true
console.log(c instanceof cat)//true 对象原型是父类也是自身的
2:构造函数
特点:
1:实现了多继承,不会共享引用类型
2:对象原型不是父类是自身的
3:call和apply参数形式书写不一样
4:可以实现传参
5:由于解决了引用类型共享问题,函数也是引用类型,所以导致函数不能共享,每一个实例化的对象,虽然功能一样,但是却不是一个函数,相当每实例一个对象,就复制了一边函数
示例:
function animal(m,n){
this.name=arguments[0];
this.sex=arguments[1];
this.hobby=[“篮球”,“足球”]
this.say=function(){}
}
function type(){
this.age=arguments[0]
}
function cat(m,n,w){
this.say=function(){}
animal.call(this,m,n)
type.apply(this,[w])
}
var c=new cat(“xiaomi”,“mu”,“24”)
var c1=new cat(“xiaomi”,“mu”,“24”)
c.hobby.push(“paiqiu”)
console.log©//cat {name: “xiaomi”, sex: “mu”, hobby: Array[3], age: “24”}
console.log(c1)//cat {name: “xiaomi”, sex: “mu”, hobby: Array[2], age: “24”}
console.log(c instanceof animal)//false
console.log(c instanceof type)//false
console.log(c instanceof cat)//true
console.log(c.say===c1.say)//false
3:组合继承(原型链继承和构造一起使用)
普通属性使用构造函数继承,函数使用原型链继承,这样即实现多继承,也实现属性独立

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值