javascriptcompositionobject-composition

Passing variables using object composition in javascript


I've been trying to wrap my head around Object Composition for a while and I can't seem to find the "correct way" to do the same I was doing before with OOP. Lets say I have a class Entity with 3 variables, with OOP I would just create a class Entity and all the children of this class would have these 3 properties, but using object composition I can't seem to understand how I'm supposed to mimic this inheritance.

const Entity = {
    let self = {
         x: 0,
         y: 0,
         z: 0,
}

Do I need to create these properties in all other objects I create that need them? Or is there a better way to reuse these properties?

const ObjectX = {
     let state = {
        x: 0,
        y: 0,
        z: 0,
        abc: 0,
        cba: 0,
return Object.assign(state, canDoX);
}

const ObjectY = {
     let state = {
        x: 0,
        y: 0,
        z: 0,
        foo: 0,
        bar: 0,
return Object.assign(state, canDoY);
}

Solution

  • If you want to extend (via prototype) some object with another object then you can use Object.create method which takes an object as argument and creates a new object with this passed in object linked to it via prototype chain.

    const entity = {
        x: 1,
        y: 2,
        z: 3
    };
    
    const objectX = Object.create(entity);
    objectX.abc = 'something';
    
    console.log(objectX.x);
    console.log(objectX.y);
    console.log(objectX.z);
    console.log(objectX.abc);

    If you just want to mix one object into another then you can use Object.assign and pass an empty object as the first argument and the entity object as the second argument to this method which will then create a new object with all the properties copied from the entity (note that this is only a shallow copy therefore you need to take some special care if that entity contains some other objects inside of it - those will be copied by reference therefore you would mutate the original ones if you would update them).

    const entity = {
        x: 1,
        y: 2,
        z: 3
    };
    
    const objectX = Object.assign({}, entity);
    objectX.abc = 'something';
    
    console.log(objectX.x);
    console.log(objectX.y);
    console.log(objectX.z);
    console.log(objectX.abc);

    Last thing, Object.assign can be replaced by object destructuring like this.

    const objectX = { ...entity };
    

    But again, this also produces only a shallow copy.