I’m trying to create a function which returns another function. I want separate information when each of the inner function is run, but this isn’t happening. I know that explanation is not great, so I’ve put together a small example.
var testFn = function(testVal) {
return (function(testVal) {
var test = testVal;
this.getVal = function() {
return test;
}
return that;
})(testVal);
}
var a = testFn(4);
var b = testFn(2);
console.log(b.getVal(), a.getVal());
This outputs 2, 2. What I would like is 2, 4 to be output. I know this isn’t explained perfectly, so if it’s not clear what I’m trying to achieve, can someone explain why the variable seems to be shared across the two functions?
Thanks
Like this ?
The problem in your code is
this.getVal()/ returningthisbecause ‘this’ refers to the global scope /
WindowYou are glubbering with the global namespace and overwriting
Window.getVal(), the moment you are settingb = testFn (2)This results in overwriting
as methodgetValtoo because they both refer to the global Object and always share the same methodgetValTherefore they share the same closure and are outputing 2
console.log("The same: " + (Window.a === Window.b)) // trueconsole.log("The same: " + (a === b)) // trueyou can see that if you change it a little:
it suddenly works because it results in 2 different Objects returned (btw you don’t even need the outer closure)
console.log("The same: " + (a === b)) // falseHere are the JSbins First / Second
I hope you understand this, I’m not good in explaining things
If theres anything left unclear, post a comment and I’ll try to update the answer