基于構造函數(shù)的五種繼承方法小結
更新時間:2017年07月27日 09:14:07 投稿:jingxian
下面小編就為大家?guī)硪黄跇嬙旌瘮?shù)的五種繼承方法小結。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
1.使用call或apply綁定構造函數(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對象。
以上這篇基于構造函數(shù)的五種繼承方法小結就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
讓回調函數(shù) showResponse 也帶上參數(shù)的代碼
讓回調函數(shù) showResponse 也帶上參數(shù)的代碼...2007-08-08

