wy57
2015-06-15 14:32:56
var Mammal=function(name){ this.name=name; }; Mammal.prototype.get_name=function(){ return this.name; }; Mammal.prototype.says=function(){ return this.saying || ""; }; var myMammal=new Mammal("Herb the Mammal"); var name=myMammal.get_name();alert(name)Function.method("inherits",function(Parent){ this.protetype=new Parent(); return this; });//這裡報(bào)錯(cuò)——沒有該方法。這個(gè)Function.method()方法不應(yīng)該是系統(tǒng)方法嗎? var Cat=function(name){ this.name=name; this.saying="meow"; } .inherits(Mammal) .method("purr",function(n){ var i,s=""; for(i=0;i<n;i+=1){ if(s){ s+="-"; } s+="r"; } return s; }) .method("get_name",function(){ return this.says()+" "+this.name+" "+this.says(); }); var myCat=new Cat("Henrietta"); var says=myCat.says();alert("says"+says) var purr=myCat.purr(5);alert(" purr"+purr) var name=myCat.get_name();alert(" name"+name)
1 回答
已采納

cwtxz
TA貢獻(xiàn)5條經(jīng)驗(yàn) 獲得超0個(gè)贊
你沒有真正理解js繼承。js里面的函數(shù)是怎么來的?其實(shí)是通過Function構(gòu)造器產(chǎn)生的,當(dāng)我們創(chuàng)建函數(shù)對象時(shí),該對象會(huì)產(chǎn)生一段類似于這樣的代碼:this.prototype={constructor:this}。method使我們?nèi)藶槎x的方法,該方法是一個(gè)輔助函數(shù),代碼如下:
????????Function.prototype.method=function(name,func){
????????????this.prototype[name]=func;
????????????return this;????
????????}
定義了該輔助函數(shù)之后,意味著所有的函數(shù)對象都可以調(diào)用method方法,而Funtion對象本身也是一個(gè)函數(shù)對象,因而也可以調(diào)用method方法。
添加回答
舉報(bào)
0/150
提交
取消