<!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繼承的三種方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.