[英]JavaScript: calling private method's property on class object
對於引擎 類 ,“ 啟動 ”和“ 停止 ”是兩個內部調用“ ignitionOn ”和“ ignitionOff ”的public methods
。 在調用“ start ”之后, private method
在engine instance
上將變量“ ignitionIndicator
”設置為“ true
”,將“ stop
”設置為“ false
”。
但是,這沒有發生。 由於“ ignitionIndicator”值始終為“ undefined”,因此出現了問題。 我必須牢記以下幾點。
(i)方法的可見性應保持原樣。
(ii)我不能直接通過public methods
設置變量。 該變量應該是並且只能從private method
。
function Engine() {
function EngineConstructor() { };
// publicly accessible methods
EngineConstructor.prototype.start = function() {
ignitionOn();
};
EngineConstructor.prototype.stop = function() {
ignitionOff();
};
// private methods
function ignitionOn() {
// does other things and sets this to true
this.ignitionIndicator = true;
};
function ignitionOff() {
// does other things and sets this to false
this.ignitionIndicator = false;
};
return new EngineConstructor();
};
var e = new Engine();
e.start();
e.ignitionIndicator // undefined, should have been true
e.stop();
e.ignitionIndicator // undefined, should have been false
你需要調用這些方法使得this
指的是一個實例,例如通過Function#call
或Function#apply
,如:
EngineConstructor.prototype.start = function() {
ignitionOn.call(this);
};
或者,只需將實例作為參數(過程樣式)傳遞:
EngineConstructor.prototype.start = function() {
ignitionOn(this);
};
// ...
function ignitionOn(instance) {
// does other things and sets this to true
instance.ignitionIndicator = true;
}
您在該代碼中使用的模式很奇怪。 您有一個函數Engine
,它用作構造函數(通過new
),但不是構造函數(它返回的不是new
運算符創建的實例),並且返回的對象與Engine
函數無關—相反,它是由EngineConstructor
創建的實例。 更糟糕的是,每次您調用它時,它都會創建一個全新的EngineConstructor
。 這是非常低效的; 如果要為每個實例重新創建所有方法,則可以做得更簡單。
但我只是重新審視整個結構,使你得到重用的方法。 如果目標是構造函數可以訪問原型方法中的私有方法,則顯示模塊模式(此處適用於單個構造函數)是通常的實現方式:
var Engine = function() { // The constructor function Engine() { } // Publicly accessible methods Engine.prototype.start = function() { ignitionOn.call(this); }; Engine.prototype.stop = function() { ignitionOff.call(this); }; // Private methods function ignitionOn() { // does other things and sets this to true this.ignitionIndicator = true; } function ignitionOff() { // does other things and sets this to false this.ignitionIndicator = false; } return Engine; }(); var e = new Engine(); e.start(); snippet.log(e.ignitionIndicator); e.stop(); snippet.log(e.ignitionIndicator);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
旁注:函數聲明沒有;
在他們之后。 ;
是一個語句終止符,而函數聲明(例如那些那些ignitionOn
和ignitionOff
聲明)不是語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.