While working on a new feature for a Javascript library, I ran into an interesting issue. It seems that when a function of an object utilizes a closure and a promise together, all instances of the object end up using the most recently created version. This causes the output of the code snippet below to be "3" repeated three times. However, introducing the var
keyword before defining logSecret
resolves the problem, resulting in the expected output of 1, 2, 3.
Why is it that multiple instances of the object share the same value?
And what exactly is the role of the var
keyword in fixing this issue?
As I'm not yet confident in my understanding of JavaScript to fully grasp the situation, I would greatly appreciate any insights or explanations on what is happening here. Thank you!
function MyObject(myValue){
var _this = this;
_this.secret = myValue;
_this.foo = function() {
makePromise = function() {
var promise = $.Deferred();
promise.resolve("done");
return promise;
}
logSecret = function() {
console.log(_this.secret);
}
var promise = makePromise();
$.when(promise).then(function (data) { logSecret(); });
}
}
var obj1 = new MyObject(1);
var obj2 = new MyObject(2);
var obj3 = new MyObject(3);
obj1.foo();
obj2.foo();
obj3.foo();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>