1. 程式人生 > >JS繼承幾種方式

JS繼承幾種方式

person fun argument per arguments 訪問 temp 共享 構造

1、原型繼承
<script>
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
alert("使用原型得到Name:"+this.name);
}
var per = new Person("dzk",21);
per.sayHello();//輸出:使用原型得到Name:dzk

function Student(){}
Student.prototype = new Person("gw",22);
var stu = new Student();

Student.prototype.grade = 5;
Student.prototype.intr=function(){
alert(this.grade);
}
stu.sayHello();//輸出:使用原型得到Name:gw
stu.intr();//輸出:5
</script>
優點:
1、非常純粹的繼承關系,實例是子類是實例,也是父類的實例,如上stu
2、父類新增原型方法or原型屬性,子類都能訪問到
3、簡單、易於實現
缺點:
1、無法實現多繼承
2、來自原型對象的引用屬性是所有實例共享的

2、構造函數繼承
<script>
function Parent(name){
this.names = name;

this.sayParent=function(){
alert("Parent:"+this.names);
}
}
function Child(name,age){
this.tempfds = Parent;
this.tempfds(name);
this.age = age;
this.sayChild=function(){
alert("Child"+this.names+"age:"+this.age);
}
}

var parent=new Parent("江劍臣");
parent.sayParent(); //輸出:“Parent:江劍臣”
var child=new Child("李鳴",24);
child.sayChild(); //輸出:“Child:李鳴 age:24”
</script>
優點:
1、解決了1中,子類實例共享父類引用屬性的問題
2、可以實現多繼承
缺點:
1、實例並不是父類的實例,只是子類的實例
2、無法實現函數復用,每個子類都有父類實例函數的副本,影響性能

3、Call、apply實現繼承
<script>
function Person(name,age,love){
this.name = name;
this.age = age;
this.love = love;
this.say=function(){
alert("姓名:"+name);
}
}
//call方式
function Student(name,age){
Person.Call(this,name,age);
}
//apply方式
function teacher(name,love){
//Person.apply(this,[name,love]);
Person.apply(this,arguments); //跟上句一樣的效果,arguments
}

//call與aplly的異同:
//1,第一個參數this都一樣,指當前對象
//2,第二個參數不一樣:call的是一個個的參數列表;apply的是一個數組(arguments也可以)

var per=new Person("武鳳樓",25,"魏熒屏"); //輸出:“武鳳樓”
per.say();
var stu=new student("曹玉",18);//輸出:“曹玉”
stu.say();
var tea=new teacher("秦傑",16);//輸出:“秦傑”
tea.say();

</script>

JS繼承幾種方式