Search code examples
javascriptecmascript-5

Assign parameters to new object in ES5 constructor using spread operator?


A constructor is accepting an options object with multiple properties. How can I assign them to the newly created object without specifying each one?

Here is my failed attempt

function Client(options) {
    const defaultOptions = { 
        host: '127.0.0.1',
        port: 1905,
        loggerFn: console.log,
        maxTime: 60000, 
        startFromTransactionId: 1 
    };
    this = { ...defaultOptions, ...userOptions, ...this }
}

ReferenceError: Invalid left-hand side in assignment

I think this works, but I hope there is a simpler solution using spread operators

function Client(options) {
    const defaultOptions = { 
        host: '127.0.0.1',
        port: 1905,
        loggerFn: console.log,
        maxTime: 60000, 
        startFromTransactionId: 1 
    };

    for (prop in defaultOptions) {
        if (defaultOptions.hasOwnProperty(prop)) {
            this[prop] = options[prop] ? options[prop] : defaultOptions[prop];
        }
    }
}

Solution

  • Using Object.assign should do the trick:

    function Client(userOptions) {
        const defaultOptions = { 
            host: '127.0.0.1',
            port: 1905,
            loggerFn: console.log,
            maxTime: 60000, 
            startFromTransactionId: 1 
        };
        Object.assign(this, { ...defaultOptions, ...userOptions });
    }