Bad example of using Object.assign () - simple example

I read the MDN docs on Object.assign()and stumbled upon one phrase that I don't understand:

The Object.assign () method copies only the listed and native properties from the source object to the target object. It uses [[Get]] for the source and [[Set]] for the target, so it will refer to getters and setters. Therefore, it assigns properties compared to simply copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. Object.getOwnPropertyDescriptor () and Object.defineProperty () should be used to copy property definitions, including their enumerability, into prototypes.

In particular, this line:

This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

I'm not quite sure what a good example to protect against use Object.assign.

+4
source share
1 answer

Getter is an accessor function for a property that returns the value of the property. Here's 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 () ---------^
Run code

Please note that when we read the value of a property example, the function starts, even if it does not look like a function call.

What this part of the MDD documents says is that Object.assignthis getter will call, it will not create an equivalent getter on the target. 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
Run code

obj example getter, obj2 example - value. Object.assign , ot obj2.example.

, 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

, (, example getter obj), .

+5

Source: https://habr.com/ru/post/1684026/


All Articles