I have a Product class. When I attempt to reference this from within a method on the class, I get an error saying this is undefined. To solve this, I have to bind this to all methods. And this, for all my classes. Here is the sample:

class Product {
    constructor() {
        this.init = this.init.bind(this);
        this.create = this.create.bind(this);
        this.update = this.update.bind(this);
        this.delete = this.delete.bind(this);
        this.getAll = this.getAll.bind(this);
        this.getOne = this.getOne.bind(this);

   * initiate microservices' calls
   init() {
       this.microserviceCalls = {
           create: 'PRODUCT:create',
           update: 'PRODUCT:update',
           delete: 'PRODUCT:delete',
           getAll: 'PRODUCT:getAll',
           getOne: 'PRODUCT:getOne',

   async create(req, res) {
   async update(req, res) {
   async delete(req, res) {
   async getAll(req, res) {
   async getOne(req, res) {

export default new Product();

My questions are

  • How can I avoid .bind(this)?
  • Is there better way to set microserviceCalls variable?
  • How can I write a base class, that will automatically implement bind(this) to all methods? Something like this:

    function bindStuff (context, props) { props.forEach(prop => { context[prop] = context[prop].bind(context); }) }


  • 1. You might get better answers on StackOverflow. This looks more like a debugging question than a software design question. 2. Regardless, are you trying to call this.*method* from within other methods in the class? All of the this.*method* = this.*method*.bind(this); lines in the constructor shouldn't be needed. How does the compiled code look? – neilsimp1 Feb 16 '18 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.