function Animal(){} Animal.prototype={ name:"animal", toString:function(){ console.log(this.name); } }; Animal.prototype.constructor=Animal; function Dog(){} //用于打破物件的參考傳遞,防止修改子類屬性對父類產生影響 var F=function(){} F.prototype=Animal.prototype Dog.prototype=new F(); Dog.prototype.constructor=Dog; Dog.prototype.name="dog"; var d=new Dog(); d.toString(); //列印子類name dog var a=new Animal(); a.toString();//列印父類name animal
上面代碼通過實體化子類和父類,分別呼叫toString()實作了繼承的關系,
這個時候有這樣的需求;不實體化父類,直接通過子類完完整整的呼叫父類的方法或屬性,
實作代碼如下
function Animal(){} Animal.prototype={ name:"animal", toString:function(){ console.log(this.name); } }; Animal.prototype.constructor=Animal; function Dog(){} //用于打破物件的參考傳遞,防止修改子類屬性對父類產生影響 var F=function(){} F.prototype=Animal.prototype Dog.prototype=new F(); Dog.prototype.constructor=Dog; Dog.prototype.name="dog"; Dog.uber=Animal.prototype; var d=new Dog(); d.toString(); //列印子類name dog //var a=new Animal(); //a.toString();//列印父類name animal /** * Dog.prototype.constructor===d.constructor */ Dog.prototype.constructor.uber.toString();//列印animal(方式1) d.constructor.uber.toString(); //列印animal(方式2)
通過面簡單的三行紅色代碼就實作了子類訪問父類成員的需求,
本來想模仿java的使用super訪問父類,后來想想super是javascript的關鍵字,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/160534.html
標籤:JavaScript
