本文歸納了 JavaScript 物件導向的幾種常見寫法,分享給大家參考。
1. 工廠方式
var Circle = function() { var obj = new Object(); obj.PI = 3.14159; obj.area = function( r ) { return this.PI * r * r; } return obj; } var c = new Circle(); alert( c.area( 1.0 ) );
2. 比較正規的寫法(建構函式 + 原型)
function Circle(r) { this.r = r; } Circle.PI = 3.14159; Circle.prototype.area = function() { return Circle.PI * this.r * this.r; } var c = new Circle(1.0); alert(c.area());
3. JSON 物件寫法
var Circle={ "PI":3.14159, "area":function(r){ return this.PI * r * r; } }; alert( Circle.area(1.0) );
4. 變化寫法(實質與第一種相同)
var Circle=function(r){ this.r=r; } Circle.PI = 3.14159; Circle.prototype={ area:function(){ return this.r*this.r*Circle.PI; } } var obj=new Circle(1.0); alert(obj.area());
其中 Circle.PI = 3.14159; 也可寫成 this.PI=3.14159;。日常最常用第一種與第三種,第三種的擴展小範例:
var show={ btn:$('.div1'), init:function(){ var that=this; alert(this); this.btn.click(function(){ that.change(); alert(this); }) }, change:function(){ this.btn.css({'background':'green'}); } } show.init();
這裡要特別注意 this 的指向問題。以動態原型方法建立自定義物件時,物件內部對屬性的存取都要帶上 this.,例如某物件有三個屬性與四個方法。但問題來了:在 $.getJSON() 這類回調方法內,this 指向的並不是物件實例,而是回調函式本身,因此若用 this.crtFindedUserID 存值,後續其他方法就拿不到。
function ContactModel() { this.crtFindedUserID = "-1"; if(typeof ContactModel._initialized == "undefined") { ContactModel.prototype.requestFindUser = function(userID) { $.getJSON(mainUrl + "User/getuserinfo",{"uid":userID},function(resultObj) { // this.crtFindedUserID = userID contactModel.crtFindedUserID = userID; }); } ContactModel._initialized = true; }; }
解法就是在回調內先取得物件實例,再對該實例的屬性賦值。同理,物件內部對視圖組件的監聽回調裡,this 指向的也是回調函式本身,要存取物件屬性同樣得透過實例而非 this。
下面是一段物件導向的標準寫法:
<script> var person=function(name,age){ this.name=name; this.age=age; } person.prototype={ getName:function(){ alert(this.name); }, getAge:function(){ alert(this.age); } } function test(){ var man=new person('jack',12); man.getName(); man.getAge(); } var test2={ te:function(){ alert(); }, te1:function(){ alert(); } } </script>
希望本文所述對大家學習 JavaScript 物件導向有所幫助。