簡體   English   中英

javascript關閉的困惑

[英]confusion of javascript closure

我正在研究JavaScript閉包。
我想用閉包進行模塊化。
所以我寫了代碼,但沒有得到想要的結果
我想要結果box1和box2不同的結果。 但是由於某種原因卻得到了相同的結果。
我該怎么辦?

 var spinBox = function() { var spinBoxConfig; return { create: function(config) { spinBoxConfig = { value: typeof config.value === 'number' ? config.value : 200 } return this; }, getValue: function() { return spinBoxConfig.value; } } }() var box1 = spinBox.create({ value: 30 }); var box2 = spinBox.create({ value: 310 }); console.log(box1.getValue()); // same console.log(box2.getValue()); // same 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

定義Spinbox對象時,只需創建一次閉合。 調用create或getValue的所有內容都將與spinBoxConfig的單個實例進行交互。 如果您想在每次調用create時創建全新的閉包,則需要在create函數中進行。

 var spinBox = { create: function (config) { var spinBoxConfig = { value: typeof config.value === 'number' ? config.value : 200 } return { getValue: function () { return spinBoxConfig.value; } } } } var box1 = spinBox.create({ value: 30 }); var box2 = spinBox.create({ value: 310 }); console.log(box1.getValue()); console.log(box2.getValue()) 

盡管確實如此,但是spinBoxconfig有點過頭了,因為您的閉包中已經有config參數,並且它具有所有相關數據。 因此,您可以這樣做:

 var spinBox = { create: function (config) { if (typeof config !== 'number') { config = 200; } return { getValue: function () { return config; } } } } var box1 = spinBox.create(30); var box2 = spinBox.create(310); console.log(box1.getValue()); console.log(box2.getValue()) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM