1

I have a very simple code with instantiated objects and I'm exposing some methods via a prototype. Here's the code:

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: 'dfvdfvd'
    };
  }

  function get() {
    return this._obj[1];
  }

  MyClass.prototype.take = () => {
    get.call(this);
  }

  return MyClass;
}());

let x = new MyClass();
console.log(x.take())

but I keep getting _obj as undefined. what am I missing here?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Das Raf
  • 55
  • 6

1 Answers1

1

The issue is that MyClass.prototype.take is an arrow function, but arrow functions don't have their own this (see MDN), thus this is the default window and this._obj is undefined. You can either bind it yourself, or just make it a regular function like I did below.

Also, make sure to return a value from MyClass.prototype.take(), or else you'll get undefined.

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: 'dfvdfvd'
    };
  }

  function get() {
    return this._obj[1];
  }

  MyClass.prototype.take = function() {
    return get.call(this);
  }

  return MyClass;
}());

let x = new MyClass();
console.log(x.take())
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 1
    wow...wouldnt have thought about it myself...so stressed out that I even forgot the `return` keyword... – Das Raf Feb 06 '23 at 00:46
  • 1
    _“but `this` is `undefined` for all arrow functions”_ — No, that’s not true. They don’t bind their own `this`, but that doesn’t mean that the value is `undefined`. – Sebastian Simon Feb 06 '23 at 01:12
  • `this` in an arrow function is bound lexically. The value of `this` immediately inside an arrow function is identical to the value of `this` immediately outside the arrow function. You cannot use `.bind` to change this value and it’s not `undefined` by default. It is whatever it is outside. – Sebastian Simon Feb 06 '23 at 01:57
  • @SebastianSimon Thanks for the good catch! I've edited my answer to correct that mistake. – Michael M. Feb 06 '23 at 01:58