**
原始繼承模式--原型鏈
過(guò)多的繼承了沒(méi)有用的屬性
2:借用構(gòu)造函數(shù)
不能借用構(gòu)造函數(shù)的原型
每次借用構(gòu)造函數(shù)都要多走構(gòu)造函數(shù)
3:共享構(gòu)造原型
不能隨便改造自己的原型
4:圣杯模式
**
一:原型鏈;
<script>
Grand.prototype.lastName='jx';
function Grand(){
}
var grand= new Grand()
Father.protptype=grand;
function Father (){}
var father=new Father()
Son.prototype=father;
function Son(){}
var son=new Son();
</script>
二:構(gòu)造函數(shù);
<script type="text/javascript">
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
function Student(name,age,sex,grade){
Person.call(this,name,age,sex){
this.grade=grade;
}
}
var student=new Student()
</script>
三:共享原型;
<script type="text/javascript">
Father.prototype.name='deng';
function Father(){
}
function Son(){
}
Son.prototype=Father.prototype;
var son=new Son();
var father= new Father();
</script>
inherit
<script type="text/javascript">
Father.prototype.lastName='yang';
function Father(){
}
function Son(){
}
function inherit(Target,Origin){
Target.prototype=Origin.prototype;
}
inherit(Son,Father);//不能寫(xiě)在var son =new Son();之后,否則不能繼承
var son =new Son();
</script>
以上的這個(gè)方法如果給他添加兒子新的屬性,如下圖,父親也會(huì)同樣繼承,以為他們都是指向同一個(gè)原型,所以為了避免這種情況,進(jìn)行如下修改
四:圣杯模式
<script type="text/javascript">
function inherit(Targer,Origin){
function F(){}
F.prototype=Origin.prototype;
Targer.prototype=new F();
}
Father.prototype.name='deng';
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son=new Son();
var father=new Father();
</script>
圣杯模式的最終代碼
<script type="text/javascript">
function inherit(Targer,Origin){
function F(){}
F.prototype=Origin.prototype;
Targer.prototype=new F();
Target.prototype.constructor=Target;//調(diào)回他自己
Target.prototype.uber=Origin.prototype;//知道誰(shuí)調(diào)用它
}
Father.prototype.name='deng';
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son=new Son();
var father=new Father();
</script>