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?
>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())