javaScript面向對象(繼承篇)
一、構造函數繼承
function Parent() { this.money = '2億' this.eat = function () { console.log('吃飯') } } function Son(name, age) { Parent.apply(this, arguments) this.name = name; this.age = age } var s = new Son("小明", 18); s.eat()//吃飯
二、prototype模式
* 通過 子類的prototype = 父類的實例來繼承
* 缺點:效率比較低,比較廢內存
function Parent() { this.money = '2億' this.eat = function () { console.log('吃飯') } } Parent.prototype.hobby = function () { console.log("旅行") } function Son(name, age) { this.name = name; this.age = age } Son.prototype = new Parent(); // 將Son的prototype對象指向一個Parent的實例。它相當于完全刪除了prototype 對象原先的值,然后賦予一個新值 /** * * 任何一個prototype對象都有一個constructor屬性,指向它的構造函數。 * 如果沒有"Son.prototype = new Parent();"這一行,Son.prototype.constructor是指向Son的;加了這一行以后,Son.prototype.constructor指向Parent。 * */ Son.prototype.constructor = Son var son = new Son("小明", 18); son.hobby()//旅行
三、直接繼承prototype
* 子類的prototype = 父類的prototype
* 缺點:子類的prototype和父類的prototype指向同一個對象,那么子類的prototype修改那么父類的prototype也會修改
function Parent() { } Parent.prototype.hobby = function () { console.log("旅行") } function Son(name, age) { this.name = name; this.age = age } Son.prototype = Parent.prototype; Son.prototype.constructor = Son; let s = new Son(); s.hobby();//旅行
四、利用空對象作為中介
* 優點:空對象幾乎不占內存,子類的prototype修改不會影響到父類prototype的改變
function Parent() { } Parent.prototype.hobby = function () { console.log("旅行") } function Son(name, age) { this.name = name; this.age = age } // function Buffer(){} //空對象 // Buffer.prototype = Parent.prototype; // Buffer.prototype.constructor = Buffer; // Son.prototype = new Buffer(); // Son.prototype.constructor = Son; // let s = new Son(); // s.hobby() /** * 對上述方法進行封裝 */ function extend(Child, Parent) { function Buffer() { }; Buffer.prototype = Parent.prototype; Buffer.prototype.constructor = Buffer; Child.prototype = new Buffer(); Child.prototype.constructor = Child } extend(Son, Parent); let s = new Son(); s.hobby()//旅行

浙公網安備 33010602011771號