Function returning objects with getters and methods

568 Views Asked by At

I was refactoring my code and decided to replace ES6-classes with this-independent factory functions. So before the changes I had something like this:

class Person {
    constructor(name) {
        this.name = name;
    }
    get myName() {
        return `My name if ${this.name}`;
    }
    say() {
        console.log(this.myName);
    }
}

const john = new Person('John');
john.say();

Then it was changed to:

 function Person(name) {
    const obj = {
        name,
        get myName() {
            return `My name if ${obj.name}`;
        },
        say() {
            console.log(obj.myName);
        },
    };
    return obj;
}

const john = Person('John');
john.say();

It worked just the same, but when I used it in my Vue app, dealing with thousands of such objects, its performance dropped dramatically. I tried to split data, getters and methods into different objects and then to return their combination { ...data, ...getters, ...methods }, but nothing changed — I saw that classes were much more performant.

After some googling I found the possibility to add getters and methods via defineProperty:

function Person(name) {
    const obj = {
        name,
    };

    Object.defineProperty(obj, 'myName', {
        get() {
            return `My name if ${obj.name}`;
        }
    });
    Object.defineProperty(obj, 'say', {
        value() {
            console.log(obj.myName);
        }
    })

    return obj;
}

const john = Person('John');
john.say();

This solution worked, the application regained its performance, but I don't understand why. The only difference is probably that now the added properties aren't enumerable. But how could that make a problem?

So I would be very grateful for an explanation and probably a better solution.

0

There are 0 best solutions below