A getter is an accessor function for a property that returns the property's value. This is what an object with a getter looks like:
var obj = {
get example() {
console.log("getter was called");
return Math.floor(Math.random() * 100);
}
};
console.log(obj.example);
// Note no () ---------^
Notice that when we read the value of the example
property, the function gets run even though it doesn't look like a function call.
What that part of the MDN docs is saying is that Object.assign
will call that getter, it won't create an equivalent getter on the target object. So:
var obj = {
get example() {
console.log("getter was called");
return Math.floor(Math.random() * 100);
}
};
var obj2 = Object.assign({}, obj); // calls getter
console.log(obj2.example); // just has a simple value
console.log(obj2.example); // same value, no call
console.log(obj2.example); // same value, no call
obj
's example
property has a getter, but obj2
's example
property is just a simple value property. Object.assign
didn't copy the getter, it just grabbed the getter's current value and assigned it ot obj2.example
.
You can copy getters, just not with Object.assign
:
function copyProperties(target, source) {
Object.getOwnPropertyNames(source).forEach(name => {
Object.defineProperty(
target,
name,
Object.getOwnPropertyDescriptor(source, name)
);
});
return target;
}
var obj = {
get example() {
console.log("getter was called");
return Math.floor(Math.random() * 100);
}
};
var obj2 = copyProperties({}, obj); // calls getter
console.log(obj2.example); // calls getter
console.log(obj2.example); // calls getter
console.log(obj2.example); // calls getter
Of course, if the getter isn't designed to be copied between objects (for instance, if example
's getter explicitly used obj
), you may get unexpected results.