I’m new to JavaScript, and am having a problem understanding this code:
function addProperty(o) {
var value;
o["get"] = function() { return value; }
o["set"] = function(v) { value = v; }
}
var a = {};
addProperty(a);
var b = {};
addProperty(b);
a.set(4);
b.set(5);
print("a is " + a.get() + "; b is " + b.get());
This prints (in v8/d8) a is 4; b is 5. If I comment out the var value; line, I get a is 5; b is 5. Where is the ‘value’ object, and why are there two of them? Thanks.
The
valuevariable is local toaddProperty. The first timeaddPropertyis called, a newvalueis created, over which both of the functions close. The second timeaddPropertyis called, a secondvalueis created over which two new functions close.Removing
varcreates a globalvalueon thewindowobject that is shared by all of the functions.Maybe you mean to do this:
This new
addPropertyfunction closes over onevalueno matter how many times it’s called. I’m not sure I understand the use case, but that should demonstrate the difference.