Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to access internal object after instantiation

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is that MyClass.prototype.take is an arrow function, but this is undefined for all arrow functions (see MDN). Just make it a regular function.

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading