基于構(gòu)造函數(shù)的五種繼承方法小結(jié)
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); // 動(dòng)物
3.直接集成prototype屬性
function Animal(){ }
Animal.prototype.species = "動(dòng)物";
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動(dòng)物
4.利用空對(duì)象作為中介
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
將上面的方法封裝成一個(gè)函數(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;
}
這個(gè)函數(shù)的作用,就是將父對(duì)象的prototype對(duì)象中的屬性,一一拷貝給Child對(duì)象的prototype對(duì)象。
以上這篇基于構(gòu)造函數(shù)的五種繼承方法小結(jié)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
javascript中setAttribute()函數(shù)使用方法及兼容性
這篇文章主要介紹了javascript中setAttribute()函數(shù)使用方法及兼容性的相關(guān)資料,需要的朋友可以參考下2015-07-07
淺談?lì)愃朴?function(){}).call()的js語句
這篇文章主要介紹了淺談?lì)愃朴?function(){}).call()的js語句,的相關(guān)資料,需要的朋友可以參考下2015-03-03
JavaScript簡(jiǎn)單實(shí)現(xiàn)網(wǎng)頁回到頂部功能
JavaScript簡(jiǎn)單實(shí)現(xiàn)網(wǎng)頁回到頂部功能,大家可以參考一下2013-11-11
layui-table對(duì)返回的數(shù)據(jù)進(jìn)行轉(zhuǎn)變顯示的實(shí)例
今天小編就為大家分享一篇layui-table對(duì)返回的數(shù)據(jù)進(jìn)行轉(zhuǎn)變顯示的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09
Express框架中_router?對(duì)象數(shù)據(jù)結(jié)構(gòu)使用詳解
這篇文章主要為大家介紹了Express框架中_router的對(duì)象數(shù)據(jù)結(jié)構(gòu)使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

