javascript
JavaScript继承
原型鏈
javascript使用原型鏈作為實(shí)現(xiàn)繼承的主要方法,實(shí)現(xiàn)的本質(zhì)是重寫原型對象,代之以一個(gè)新類型的實(shí)例
function Super(){this.value = true; } Super.prototype.getValue = function(){return this.value; }; function Sub(){} //Sub繼承了Super Sub.prototype = new Super(); Sub.prototype.constructor = Sub;var instance = new Sub(); console.log(instance.getValue());//true原型鏈最主要的問題在于包含引用類型值的原型屬性會被所有實(shí)例共享,而這也正是為什么要在構(gòu)造函數(shù)中,而不是在原型對象中定義屬性的原因。在通過原型來實(shí)現(xiàn)繼承時(shí),原型實(shí)際上會變成另一個(gè)類型的實(shí)例。于是,原先的實(shí)例屬性也就順理成章地變成了現(xiàn)在的原型屬性了
原型式繼承
原型式繼承借助原型可以基于已有的對象創(chuàng)建新對象,同時(shí)還不必因此創(chuàng)建自定義類型。從本質(zhì)上講,object()對傳入其中的對象執(zhí)行了一次淺復(fù)制
function Super(){this.value = 1; } Super.prototype.value = 0; function Sub(){};Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub;//創(chuàng)建子類型的實(shí)例對象 var instance = new Sub; console.log(instance.value);//0Object.create()創(chuàng)建一個(gè)空對象,這個(gè)空對象的原型指向Object.create()這個(gè)函數(shù)的參數(shù)。通過這個(gè)方法,子類可以繼承父類的原型上的屬性,避免了繼承父類的實(shí)例上的屬性,解決了原型鏈繼承的弊端。
構(gòu)造函數(shù)式繼承
借用構(gòu)造函數(shù)的技術(shù),在子類型構(gòu)造函數(shù)的內(nèi)部調(diào)用父類型構(gòu)造函數(shù),通過使用apply()和call()方法在新創(chuàng)建的對象上執(zhí)行構(gòu)造函數(shù),還可以傳遞參數(shù)。
function Super(name){this.name = name; } function Sub(){//繼承了Super,同時(shí)還傳遞了參數(shù)Super.call(this,"bai");//實(shí)例屬性this.age = 29; } var instance = new Sub(); console.log(instance.name);//"bai" console.log(instance.age);//29組合式繼承
指的是將原型式繼承和構(gòu)造函數(shù)式繼承的技術(shù)組合到一塊,從而發(fā)揮二者之長的一種繼承模式。其背后的思路是使用原型式繼承實(shí)現(xiàn)對原型屬性和方法的繼承,而通過構(gòu)造函數(shù)式繼承來實(shí)現(xiàn)對實(shí)例屬性的繼承。
function Super(name){this.name = name;this.colors = ["red","blue","green"]; } Super.prototype.sayName = function(){return this.name; };function Sub(name,age){Super.call(this,name);this.age = age; }Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub;var instance1 = new Sub("bai",29); instance1.colors.push("black"); console.log(instance1.colors);//['red','blue','green','black'] instance1.sayName();//"bai"var instance2 = new Sub("hu",27); console.log(instance2.colors);//['red','blue','green'] instance2.sayName();//"hu"ES6 extends
定義一個(gè)類
class Point{constructor(x, y){this.x = x;this.y = y;}toString(){return '點(diǎn)坐標(biāo): ' + this.x + ',' + this.y;} } let fp = new Point(12, 34); console.log(fp.toString()); //"點(diǎn)坐標(biāo): 12,34"extends繼承
class ColoredPoint extends Point{constructor(x, y, color){super(x, y);this.color = color;}toString(){return this.color + super.toString();} } let sp = new ColoredPoint(56, 78, '紅色'); console.log(sp.toString()); //"紅色點(diǎn)坐標(biāo): 56,78"super指代父類的實(shí)例(父類的this對象)
總結(jié)
以上是生活随笔為你收集整理的JavaScript继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 饿了么如何连接美团打印机(3年前将饿了么
- 下一篇: 提高JS性能注意事项(转载)