JS中的繼承操作實例總結
本文實例講述了JS中的繼承操作。分享給大家供大家參考,具體如下:
1.原型鏈繼承function SuperType() { this.property = true; }SuperType.prototype.getSuperValue = function() { return this.property;}function SubType() { ths.subproperty = false;}SubType.prototype = new SuperType(); // 實現繼承SubType.prototype.getSubValue = function() { return this.subproperty;}var instance = new SubType();console.log(instance.getSuperValue()); // true
原理:讓SuperType的實例成為子類的原型對象,子類的實例擁有了父類的屬性和方法。但也有弊端,如果父類的屬性是引用類型,這將導致共享的屬性被改變的時候,全部的屬性將被改變,我們一下代碼。
function SuperType() { this.property = [1,2,3]; }SuperType.prototype.getSuperValue = function() { return this.property;}function SubType() { ths.subproperty = false;}SubType.prototype = new SuperType(); // 實現繼承SubType.prototype.getSubValue = function() { return this.subproperty;}var instance1 = new SubType();var instance2 = new SubType();instance1.property.push(4);console.log(instance1.property); // [1,2,3,4]console.log(instance2.property); // [1,2,3,4]
我們修改一處的實例屬性,兩個實例的屬性都會被修改,因為這個屬性是共享的,這也是原型鏈繼承的缺點。
2.構造函數繼承function SuperType(name) { this.name = name; this.numbers = [1,2,3];}function SubType() { SuperType.call(this,'Nicholas'); this.age = 29;}var instance1 = new SubType();var instance2 = new SubType();instance1.property.push(4);console.log(instance1.name); // Nicholasconsole.log(instance1.age); // 29console.log(instance1.numbers); // [1,2,3,4]console.log(instance2.numbers); // [1,2,3]
在子類中調用父類的構造函數,每次實例化時都會新建父類的屬性放在新實例中,因此每個實例中的屬性都是不一樣的,改變一個實例的值不會造成另一個實例的值改變。這個繼承方式的缺點是方法的定義不能復用。
3.組合繼承這個方法將原型鏈繼承和構造函數繼承結合到一起,融合了他們各自的優點。
function SuperType(name) { this.name = name; this.colors = ['red','blue','green']}SuperType.prototype.sayName = function() { console.log(this.name);}function SubType(name,age) { SuperType.call(this,name); this.age = age;}SubType.prototype = new SuperType();SubType.prototype.constructor = SubType;SubType.prototype.sayAge = function() { console.log(this.age);}var instance1 = new SubType('Nicholas', 29);var instance2 =new SubType('Greg', 27);instance1.colors.push('black');console.log(instance1.colors); // red,blue,green,blackconsole.log(instance2.colors); // red,blue,greeninstance1.sayName(); // Nicholasinstance2.sayName(); // Greginstance1.sayAge(); // 29instance2.sayAge(); // 27 4.class繼承
ES6中可以通過class創建對象,通過關鍵字extends繼承。
class Point { constructor(x, y) { this.x = x; this.y = y; }}class ColorPoint extends Point { constructor(x, y, color) { this.color = color; // ReferenceError super(x, y); this.color = color; // 正確 }}
在ES6的繼承中,子類一定要重寫父類的構造函授的方法,否則會報錯。
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章:
