Reputation: 358
Based on the following way of encapsulating the variable productId
, are calls to ProductId.get()
guaranteed to return the previously set value or could the value have potentially been garbage collected and therefore be undefined?
var ProductId = (function () {
var productId = -1;
return {
get: function () {
return productId;
},
set: function (val) {
productId = parseInt(val, 10);
}
};
})();
If for example I call ProductId.set(1234)
and then, some time later, call ProductId.get()
, could it have been GC?
It seems, though I'm not 100% sure, that there is no, direct reference to the encapsulated variable productId and therefore it will be GC.
Upvotes: 2
Views: 43
Reputation: 69
productId will be accessible in any time of script usage, it's classical example of closures, get and set methods will still have access to productId variable even after anonymous function will be executed.
Upvotes: 1