Given the following code are foo
, bar
and baz
all effectively the same? What if any is the advantage of using the get
keyword?
var getValue = function () {
return 'value';
}
var foo = {
value: getValue(),
};
var bar = {
get value() {
return getValue();
},
};
var baz = {
get value() {
return 'value';
},
};
console.log('foo.value', foo.value); // foo.value value
console.log('bar.value', bar.value); // bar.value value
console.log('baz.value', baz.value); // baz.value value
Given the following code are foo, bar and baz all effectively the same?
No, not at all.
foo
will have a value
property that will be the result of calling getValue
when foo
was created, and will not call getValue
later.
bar
will have a value
property that, when accessed like bar.value
, calls getValue
and returns its return value.
baz
will have a value
property with the explicit value 'value'
.
The differences are:
getValue
is calledgetValue
is calledThis is more obvious with some logging and with a slightly updated version of getValue
:
var getValue = function () {
var value = Math.floor(Math.random() * 1000);
console.log("getValue called, returning " + value);
return value;
}
console.log("Creating foo");
var foo = {
value: getValue(),
};
console.log("Creating bar");
var bar = {
get value() {
return getValue();
},
};
console.log("Creating baz");
var baz = {
get value() {
return 42;
},
};
console.log("Calling foo");
console.log('foo.value', foo.value);
console.log("Calling bar");
console.log('bar.value', bar.value);
console.log("Calling baz");
console.log('baz.value', baz.value);
.as-console-wrapper {
max-height: 100% !important;;
}
The advantage (and disadvantage) to a getter is you can execute logic (such as calling getValue
) in response to what looks like a simple property lookup (bar.value
, rather than bar.value()
or bar.getValue()
).