构造函数的五种继承方法
1、使用call或apply綁定構(gòu)造函數(shù)
animal.apply(this.arguments)
2、使用prototype屬性
Cat.prototype=new Animal();
Cat.prototype.constructor=Cat;
var cat1=new Cat("大毛","黃色");
alert(cat1.species);//動物
3、直接集成prototype屬性
function Animal(){}
Animal.prototype.species="動物";
Cat.prototype=Animal.prototype;
Cat.prototype.constructor=Cat;
var cat1=new Cat("大毛","黃色");
alert(cat1.species);//動物
4、利用空對象作為中介
var F=function(){};
F.prototype=Animal.prototype;
Cat.prototype=new F();
Cat.prototype.constructor=Cat;
將上面的方法封裝成一個函數(shù),便于使用:
function extend(Child.Parent){
var F=function(){};
F.prototype=Parent.prototype;
Child.prototype=new ?F();
Child.prototype.constructor=Child;
Child.uber=Parent.prototype;
}
5、拷貝繼承
function extend2(Child.Parent){
? var p=Parent.prototype;
?var c=Child.prototype;
for(var i in p){
? ? ?c[i]=p[i];
}
c.uber=p;
}
這個函數(shù)的作用,就是將父對象的prototype對象中的屬性--拷貝給Child對象的prototype對象
?
轉(zhuǎn)載于:https://www.cnblogs.com/zzp0320/p/7245138.html
總結(jié)
以上是生活随笔為你收集整理的构造函数的五种继承方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (一)svn介绍
- 下一篇: 全局变量和环境变量的区别