70656e6973 70656e6973 - 7 months ago 12
Javascript Question

Call instance method from instance method

I'd like to call method1 from within method2. Not sure how to access it. I receive:


TypeError: Cannot call method 'method1' of undefined


TestSchema.methods = {
method1: () => {
return true;
},
method2: () => {
if(this.method1()){
console.log('It works!');
}
}
};

Answer

Do not use the arrow function. It uses the this context from the lexical scope of the function definition. And it's undefined in the strict mode you're using.

Use regular functions:

TestSchema.methods = {
  method1: function() {
      return true;
  },
  method2: function() {
    if(this.method1()){
        console.log('It works!');
    }
  }
};

And then make sure to call the function as a method on the object:

TestSchema.methods.method2();