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()實現了繼承的關係。javascript
這個時候有這樣的需求;不實例化父類,直接經過子類完完整整的調用父類的方法或屬性。java
實現代碼以下this
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)
經過面簡單的三行紅色代碼就實現了子類訪問父類成員的需求。spa
原本想模仿java的使用super訪問父類,後來想一想super是javascript的關鍵字。prototype