2014-09-20 107 views
1
var Command = function() { 
     var _self = this, 

     //flag to indicate that the operation is running 
     _isRunning = ko.observable(false), 

     //property to save the error message 
     _errorMessage = ko.observable(); 

     //public properties 
     this.isRunning = _isRunning; 
     this.errorMessage = _errorMessage; 
}; 

爲什麼此示例同時使用私有變量和公共變量?這是我們所遵循的設計模式嗎?爲什麼我們分別使用公共和私有變量

回答

2

在你剛剛引用的代碼中,沒有任何理由。但我的猜測是,後來在最外面的功能,你有這樣的事情:

this.doSomething = function() { 
    if (_isRunning()) { 
     // do one thing 
    } else { 
     // do something else 
    } 
}; 

之所以具有局部變量是如此,它並不重要this值的函數調用。

也就是說,_self變量已經爲您解決了這個問題,使得_isRunning_errorMessage變量純粹是便利的別名。以上也可以同樣是:

this.doSomething = function() { 
    if (_self.isRunning()) { 
     // do one thing 
    } else { 
     // do something else 
    } 
}; 

這裏沒有具體的設計模式,它只是使用一個事實,即在其他函數中創建的函數是函數在局部變量關閉(和一些其他的東西),他們'創建英寸

相關問題