JavaScript 並不像傳統物件導向語言那樣有明確的類別語法,但可透過多種方式模擬。本文整理了四種常見的類別定義方式,供大家參考。
function createCar(name,color,price){ var tempcar=new Object; tempcar.name=name; tempcar.color=color; tempcar.price=price; tempcar.getName=function(){ document.write(this.name+"-----"+this.color+"<br>"); }; return tempcar; } var car1=new createCar("工廠桑塔納","red","121313"); car1.getName();
這種方式定義了一個能建立並回傳特定物件的工廠函式,看起來還不錯,但有個小問題:每次呼叫都要建立新函式 getName。我們可以把它移到函式外面:
function getName(){ document.write(this.name+"-----"+this.color+"<br>"); }
再在工廠函式中直接指向它:tempCar.getName = getName;。這樣避免了重複建立函式,但看起來就不太像物件的方法了。
function Car(name,color,price){ this.name=name; this.color=color; this.price=price; this.getColor=function(){ document.write(this.name+"-----"+this.color+"<br>"); }; } var car2=new Car("構造桑塔納","red","121313"); car2.getColor();
與第一種方式的差別在於,建構函式內部不建立物件,而是使用 this 關鍵字。以 new 呼叫時會先建立一個物件,再用 this 存取。這種用法與其他物件導向語言很相似,但仍有重複建立函式的問題。
function proCar(){ } proCar.prototype.name="原型"; proCar.prototype.color="blue"; proCar.prototype.price="10000"; proCar.prototype.getName=function(){ document.write(this.name+"-----"+this.color+"<br>"); }; var car3=new proCar(); car3.getName();
這種方式先定義一個空的建構函式,再透過 prototype 添加屬性。優點是:所有實例存放的都是指向 getName 的指標,解決了重複建立函式的問題;且可用 instanceof 檢查物件型別:
alert(car3 instanceof proCar);//true
缺點則是,若加入下面的程式碼:
proCar.prototype.drivers = newArray("mike", "sue"); car3.drivers.push("matt"); alert(car3.drivers);//outputs "mike,sue,matt" alert(car3.drivers);//outputs "mike,sue,matt"
可以發現 drivers 是指向 Array 物件的指標,proCar 的所有實例都指向同一個陣列,改動會互相影響。
function autoProCar(name,color,price){ this.name=name; this.color=color; this.price=price; this.drives=new Array("mike","sue"); if(typeof autoProCar.initialized== "undefined"){ autoProCar.prototype.getName =function(){ document.write(this.name+"-----"+this.color+"<br>"); }; autoProCar.initialized=true; } } var car4=new autoProCar("動態原型","yellow","1234565"); car4.getName(); car4.drives.push("newOne"); document.write(car4.drives);
這種方式是我個人最喜歡的:所有類別定義都在同一個函式中完成,看起來非常像其他語言的類別定義,既不會重複建立函式,也能用 instanceof 檢查型別。
希望本文所述的內容能對大家學習 JavaScript 有所幫助。