- 論壇徽章:
- 0
|
js是一個很自由的語言,沒有強類型的語言的那種限制,實現(xiàn)一個功能往往有很多做法。繼承就是其中的一個,在js中繼承大概可以分為四大類,下面開始詳細說說js的繼承。
1、原型繼承
function funcA(){
this.show=function(){
console.log("hello");
}
}
function funcB(){
}
funcB.prototype=new funcA();
var b=new funcB();
b.show();
這里是運用原型鏈的特性實現(xiàn),缺點很明顯,如果繼承的層次比較多的話,修改頂層的原型的方法,會對下面所有的對象產(chǎn)生影響。
2、原型冒充:
function funcA(age){
this.name="xiaoxiao";
this.age=age;
this.show=function(){
console.log(this.name+this.age)
}
}
function funcB(){
this.parent=funcA;
this.parent(40);
delete this.parent;
}
var b=new funcB();
b.show();
這個繼承的方法就是把funcA中的代碼全部拿到funcB中執(zhí)行一下,可以解釋成:
function funcA(age){
this.name="xiaoxiao";
this.age=age;
this.show=function(){
console.log(this.name+this.age)
}
}
function funcB(){
// this.parent=funcA;
// this.parent(40);
// delete this.parent;
//其實上面的過程只不過是把funcA搬過來
this.name="xiaoxiao";
this.age=age;
this.show=function(){
console.log(this.name+this.age)
}
}
var b=new funcB();
b.show();
3、call和apply
function funcA() {
this.show = function(str) {
console.log(str);
}
}
function funcB() {
this.read = function() {}
}
var a = new funcA();
var b = new funcB();
funcA.call(b);//use call
a.show("a");
b.show("b");
call和apply效果是一樣的,不過是傳參方式上不一樣,但是推薦用call,因為apply的效率會低很多。
4、復(fù)制繼承
function funcA(){
this.name="hello";
this.show=function(){
console.log(this.name);
}
}
function funcB(){
this.extend=function(o){
for(var p in o){
this[p]=o[p];
}
}
}
var a=new funcA();
var b=new funcB();
b.extend(a);
b.show();
這個類似于jquery的extend的方法,原理是把a中的屬性遍歷到b中。
|
|