The following constructor function is written in JavaScript / ES5 -
function Range(from, to) {
function getFrom() { return from; }
function getTo() { return to; }
function setFrom(f) { from = f; }
function setTo(t) { to = t; }
Object.defineProperties(this, {
fromProp: { get: getFrom, set: setFrom, enumerable: true, configurable: false },
toProp: { get: getTo, set: setTo, enumerable: true, configurable: false }
});
};
I create an object using this constructor as follows -
var range = new Range(4, 13);
My general understanding of object creation is, there should be some code inside the constructor that, after instantiating the object range
, will initialize fromProp
and toProp
with the values I passed through the parameters to the constructor. But I'm having hard time understanding how exactly that is happening here.
Or, is it that the whole "initializing/accessing property" things here are captured inside the closure of setter/getter invocation? But if so, then at any time when I use -
range.fromProp = 22;
the value 22 actually never gets set to the range
object's property fromProp
, but rather to the parameter variable from
, and then whenever I ask for -
var fromValue = range.fromProp;
it just hands me over the current value of the parameter variable from
. Am I getting this right, or missing something?
Any explanation on the matter?