<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// 1、原型继承
//原型继承的特点:既继承了父类的模板,又继承了父类的原型对象
// 父类 构造函数 sup
function Sup(name,sex){
this.name = name;
this.sex = sex;
}
// 父类原型对象
Sup.prototype = {
constructor:Sup,
sayName:function(){
alert(this.name)
}
}
// 子类构造函数
function Son(age){
this.age = age;
}
Son.prototype = new Sup("zj");
var b = new Son();
alert(b.name);
b.sayName();
// 2、类继承(只继承父类的模板,不继承原型对象)
// 父类 构造函数 sup
function Sup(name,sex){
this.name = name;
this.sex = sex;
}
// 父类原型对象
Sup.prototype = {
constructor:Sup,
sayName:function(){
alert(this.name)
}
}
// 子类构造函数
function Son(name,sex,age){
// call applay
Sup.call(this,name,sex);
this.age = age;
}
var b = new Son("zj","male",20);
alert(b.name+b.sex+b.age);
// b.sayName();不继承原型对象
// 3.混合继承(原型继承 + 借用构造函数继承)
// 父类 构造函数 sup
function Sup(name,sex){
this.name = name;
this.sex = sex;
}
// 父类原型对象
Sup.prototype = {
constructor:Sup,
sayName:function(){
alert(this.name)
}
}
// 子类构造函数
function Son(name,sex,age){
// call applay
Sup.call(this,name,sex);//借用构造函数继承 继承父类模板
this.age = age;
}
// 接下来继承原型
Son.prototype = new Sup();//继承父类的原型对象
var b = new Son("zj","male",20);
alert(b.name+b.sex+b.age);
b.sayName();//继承原型对象
</script>
</body>
</html>
js继承的三种方式
最新推荐文章于 2023-11-01 20:22:50 发布