在js中實現的繼承的方法可以有多種,除了原型繼承之後,還可以使用借用、僞造構造函數的方法實現繼承等等。接下來我們就詳細的介紹一下這幾種方式。
1.js中的原型繼承
<script type="text/javascript">
function Person(name,age){
this.name=name;
this.age=age;
}
function Teacher(name,sex){
this.name=name;
this.sex=sex;
}
Person.prototype.show="kk";
//實現原型繼承
Teacher.prototype=new Person();
var t1=new Teacher("aa","男");
//使用Person原型中的屬性
console.log(t1.show);
</script>
2.借用、僞造構造函數的方式實現繼承
<script type="text/javascript">
function Person(name,age){
this.name=name;
this.age=age;
}
function Teacher(sex,name,age){
Person.call(this,name,age);
this.sex=sex;
}
var t1=new Teacher("男","cc",30);
console.log(t1.sex);
console.log(t1.name);
console.log(t1.age);
</script>
3.總結比較兩種繼承方法
4.基於這兩種方式實現的繼承--組合方式繼承
<script type="text/javascript">
function Person(name,age){
this.name=name;
this.age=age;
}
function Teacher(sex,name,age){
Person.call(this,name,age);
this.sex=sex;
}
Person.prototype.show="kk";
Teacher.prototype=new Person();
var t1=new Teacher("男","cc",30);
console.log(t1.sex);
console.log(t1.name);
console.log(t1.age);
console.log(t1.show);
</script>