Search code examples
javascriptnode.jsmixins

javascript mixin access to objects this


I've created an object and a mixin, i've assigned the mixin to the Object, but I don't have access to the object from the mixin , it seems?

mixin.js

module.exports = {
  doSomething: () => {
    let something = this.something.title;
  }
};

object.js

class Thing {   
  constructor(something) {
    this.something = something;   
  }

  _otherFunction() {
    // does stuff
  } 
}

module.exports = Thing;

index.js

const Something = require('./mixin');
const Thing = require('./Object');

Object.assign(Thing.prototype, Something);

when I then instantiate Thing and call doSomething(), it then can't get access to this.something... so

let thing = new Thing({title: 'abc'});
thing.doSomething();

i get the error Cannot read property 'title' of undefined


Solution

  • You need to ditch the arrow function, in favour of a vanilla function, because the arrow function loses the scope of this.

    class Thing {   
      constructor(something) {
        this.something = something;   
      }
    }
    
    const mixin = {
      // changed arrow function to regular function
      doSomething: function () {
        console.log(this.something.title)
      }
    }
    
    const thing = new Thing({title: 'abc'})
    Object.assign(thing, mixin)
    thing.doSomething()

    From MDN: Arrow Functions:

    An arrow function expression... and does not have its own this, arguments, super, or new.target.

    A lot of people mistakenly believe that the sole feature of an arrow function is shorter syntax - it's not. It's primary practical feature is that it doesn't create it's own this.