對象,具有屬性與方法。這是大家都聽到爛的話了。物件導向的基本特徵有:封閉、繼承、多態。今天來我總結一下我剛剛學到的,我只是把看到的冰山一角寫下來了,希望可以完善。
對象的繼承相信大家都很熟悉了。可以用對象冒充、call()[apply()]、原型方式、混合方式這幾種。其中混合方式我覺得是比較好的,先開回顧一下call()方法:
function useCall(a,b){ this.a = a; this.b = b; this.say=function(){ alert("I'm "+this.a+" You're"+this.b); } } function callThefunction (){ var args = arguments; useCall.call(this,args[0],args[1]); // useCall.apply(this,arguments); }var testCall1 =new useCall("Not YY","Not TT");testCall1.say();var testCall2 = new callThefunction("YY","TT");testCall2.say();
原型方式:
function car(price){ this.price=price;}car.prototype={ sayPrice:function(){console.log("Price is "+this.price);} //console.log()參見Firebug API}function toyCar(price){ this.price=price;}toyCar.prototype=new car()var oCar=new car("100W");oCar.sayPrice();var oCar2=new toyCar("10CNY");oCar2.sayPrice();
混合方式:
function house(size,price){ this.size = size; this.price = price; } house.prototype.showArea=function (){ console.log("面積為"+this.size); } house.prototype.sayPrice=function (){ console.log("價錢為"+this.price); }function maofan(size,price){ house.call(this,size,price);}maofan.prototype=new house();var newmaofan=new maofan("20Square meters ","1000CNY");newmaofan.showArea();
混合方式另一種寫法:
function house(size,price){ this.size = size; this.price = price; } house.prototype={ showArea:function(){ console.log("面積為"+this.size); }, sayPrice:function(){ console.log("價錢為"+this.price); }}function maofan(size,price){ house.call(this,size,price);}maofan.prototype=new house();var newmaofan=new maofan("20 Square meters ","1000CNY");newmaofan.showArea();newmaofan.sayPrice();
為繼承的對象追加一個方法試試:
function house(size,price){ this.size = size; this.price = price; } house.prototype={ showArea:function(){ console.log("面積為"+this.size); }, sayPrice:function(){ console.log("價錢為"+this.price); }}function maofan(size,price){ house.call(this,size,price);}maofan.prototype=new house();maofan.prototype.Sayid=function(id){ //在繼承了之後再添加方法,不然就出錯了,找不到方法 this.id = id; console.log("ID is:"+this.id);}var newmaofan=new maofan();newmaofan.Sayid("888");//Output ID:888
幾個例子,都可以去試一下。我從來沒想過高手會看這些文章,只是寫之前剛入門的。所以要是寫的不好就不要見怪了。這些Demo只要試過了,加上你查的資料應該對這個JavaScript繼承這一塊就熟悉了。值得說的是,有很多的寫法,我們新手是沒見過的。像混合方式的另一種寫法,我是不經常這樣用。在我看來就是一個數組,這樣理解會好很多。例子看多了,看難的例子就不會暈。不過我看到長的還是會暈,還會出現_string_這種,雖然沒什麼了不起,看得心裡不明白就不想看下去了。所以,要學真功夫還是沒這麼簡單的。
還忘了一點,在寫call()的時候,我一開始是這樣寫的:xxx.call(this,a,b);但是這樣卻報錯了。為什麼呢?這裡要謝謝JS群裡的司馬閑大哥,call(thisobj,args[0]…)。如果像我那樣寫,不僅是參數不對,還有就是根本亂用參數。