0

I have an object that holds sub-objects. Some of these sub objects want to inherit from other sub objects, like below:

const actions = {
    global: {
        name: 'Global',
        setActionSet: (socket, newActionSet) => {
            sockets.actions = newActionSet;
        }
    },

    unregisteredSocket: {
        ...this.global,
        name: 'Unregistered',
        register: (socket, newActionSetName) => {
            socket.actions.setActionSet(socket, actionGroups[newActionSetName]);
        }
    },

    registeredSocket: {
        ...this.global,
        name: 'registered',
        setActionSet: (socket, newActionSet) => { /* something different from when it is unregistered */ },
        // ...
    }
}

I want to have both registeredSocket and unregisteredSocket to inherit the default setActionSet, and overwrite setActionSet within registeredSocket. However, when I run the program, unregisteredSocket does not inherit from global like I thought it would - none of global's members are unpacked into unregisteredSocket's. registeredSocket has setActionSet, but it is the one that was redefined.

This causes calling socket.actions.setActoinSet in the register of unregisteredSocket to fail, as setActionSet has not been defined.

Jon
  • 2,566
  • 6
  • 32
  • 52

1 Answers1

1

In your code, this does not refer to the actions object, it refers to window. That's why the spread operator does nothing, because this.global is undefined.

This does what you want:

const global = {
    name: 'Global',
    setActionSet: (socket, newActionSet) => {
        sockets.actions = newActionSet;
    }
};

const actions = {
    global,
    unregisteredSocket: {
        name: 'Unregistered',
        register: (socket, newActionSetName) => {
            socket.actions.setActionSet(socket, actionGroups[newActionSetName]);
        },
        ...global
    },

    registeredSocket: {
        name: 'registered',
        setActionSet: (socket, newActionSet) => { /* something different from when it is unregistered */
        },
        ...global
        // ...
    }
}

Note that the order matters when you define several times the same property of an object (only the last one counts).

Guerric P
  • 30,447
  • 6
  • 48
  • 86