简体   繁体   中英

confusion of javascript closure

I am studying JavaScript closure.
I want to modularize with closure.
So I wrote the code and I did not get the results I wanted
I want different results for result box1 and box2. But for some reason getting same results.
what should I do?

 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> 

You're creating a closure once, when you define the spinbox object. Everything that calls create or getValue will be interacting with that single instance of spinBoxConfig. If you want to create brand new closures every time you call create, you'll need to do so in your create function.

 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()) 

Though really, that spinBoxconfig is kind of overkill, since you already have the config param in your closure and it has all the relevant data. So you could do this:

 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()) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM