2012-12-06 59 views
0

我目前使用下面的模式來創建要使用的JS模塊。但是,我無法弄清楚在第一種風格和第二種風格之間是否有任何區別或任何好處。這兩種聲明JS屬性的方法之間的區別

1路

var UI = UI || {}; 
(function() { 
var BtnShape = function (x, y, width, height, size, color, text) 
{ 
    this.initialise(x, y, width, height, size, color, text); 
} 
var p = BtnShape.prototype; 

    p.isEnabled = false; //<-------------- 
    p.initialise = function (x, y, width, height, size, color, text) 
    {} 
UI.BtnShape = BtnShape; 
})(); 

第二方式

var UI = UI || {}; 
(function() { 
var BtnShape = function (x, y, width, height, size, color, text) 
{ 
    this.initialise(x, y, width, height, size, color, text); 
} 
var p = BtnShape.prototype; 

    p.initialise = function (x, y, width, height, size, color, text) 
    { 
      this.isEnabled = false; //<--------------- 
    } 
UI.BtnShape = BtnShape; 
})(); 

回答

3

我在這裏可以看到的唯一區別是isEnabled屬性的設置順序。通過將isEnabled屬性嵌套到初始化函數中,您需要在isEnabled有任何值之前運行initalise過程。我假設你會在做任何事情之前運行初始化函數,但是如果你不這樣,那麼isEnabled將是空的。

3

1路:isEnabledfalse,無論你叫initialise()與否。

第二個辦法:isEnabledfalse只有當你叫initialise()undefined否則。

1

在第一種方式,它是默認不啓用(但不是未定義)

// After all your code 
var x= BtnShape.prototype; 
// Here x is not enabled . If you want to enable it, you need to do it separately like below. 
p.isEnabled = true; 

在第二種方式,當你初始化對象,默認情況下它變成假的。除非你初始化,否則如果你初始化,它就會被撥號。你需要單獨啓用它。

var y =BtnShape.prototype; 
// Here if you don't initialize the object y, then isEnabled is undefined. 
相關問題