OLOO (Objects Linking to Other Objects)

OLOO (Objects Linking to Other Objects)

Andrew Velez
Posted on 9/27/2019Last Modified: 9/27/2019


    const Test = {
      create() {
        // the first Object Literal always uses Object.create since this allows to reuse function memory.
        const test = Object.create(Test);
        return test;
      },
      inheritedObject: 0,
      get meme() {

      },
      method1() {
        console.log('Test');
      }
    }

    const Test2 = {
      create() {
        return ObjectAssign(Test.create(), Test2);
      },
      inherited2: 0,
      get meme() {
        return 0;
      },
      get meme2() {

      },
      method1() {
        console.log('Test2');
      }
    }

    const Test3 = {
      create() {
        return ObjectAssign(Test2.create(), Test3);
      },
      inherited3: 0,
      method1() {
        console.log('Test3');
      },
      method2() {
        Object.getPrototypeOf(Object.getPrototypeOf(this)).method1();
      }
    }

    // This works all properties need to be high level while funcitons are in prototype.
    const test = Test.create();
    const test2 = Test2.create();
    const test3 = Test3.create();
    test.method1();
    // "Test"
    test2.method1();
    // "Test2"
    test3.method1();
    // "Test3"
    test3.method2();
    // "Test2"

// Works the same as Object.assign but allows getters and setters.
function ObjectAssign(target, ...sources) {
  let createdPrototype = false;

  sources.forEach(source => {
    let descriptors = Object.keys(source)
      .reduce((descriptors, key) => {
        const descriptor = Object.getOwnPropertyDescriptor(source, key);

        if(typeof descriptor.get === 'undefined' && typeof source[key] === 'function') {
          if(!createdPrototype) {
            createdPrototype = true;
            Object.setPrototypeOf(target, Object.create(target.__proto__));
          }
          target.__proto__[key] = source[key];
          return descriptors;
        }

        descriptors[key] = descriptor;
        return descriptors;
      }, {});

    // by default, Object.assign copies enumerable Symbols too
    Object.getOwnPropertySymbols(source)
      .forEach(sym => {
        let descriptor = Object.getOwnPropertyDescriptor(source, sym);
        if (descriptor.enumerable) {
          descriptors[sym] = descriptor;
        }
      });

    Object.defineProperties(target, descriptors);
  });

  return target;
}

module.exports = ObjectAssign;

You could chose to polyfill Object.prototype.assign to be ObjectAssign so that you can use it for inheriting.

Andrew Velez
Posted on 9/27/2019Last Modified: 9/27/2019

...

Recomendations

Games for Sale

Comments 0

Display Name

Email


0 / 10