skip to Main Content

I want to use object literal notation to generate a namespace:

const featureGoogleAnalytics = {
  gTagId: 'G-XXXXXXX', // Your Google Analytics ID

...

  resetConsent: () => { // eslint-disable-line no-unused-vars
    localStorage.removeItem('googleAnalyticsConsent');
...
    return false;
  },


  /**
   * Initializes feature Google Analytics
   * Supposed to run after poageload, callback for $( () => { ... } );
   */
  init: () => { 
    this.resetConsent();
    ...
  },
};

Now the line

this.resetConsent();

Errors with

Uncaught TypeError: this.resetConsent is not a function

What did I miss? I assume the syntax of calling the resetConsent function is wrong, but I wasn’t able to Google it.

2

Answers


  1. The syntax is:

    featureGoogleAnalytics.resetConsent();
    Login or Signup to reply.
  2. From comments, don’t use an anonymous function wrapper in an Object definition.

    const featureGoogleAnalytics = {
      gTagId: 'G-XXXXXXX', // Your Google Analytics ID
    
    ...
    
      resetConsent: function() { // eslint-disable-line no-unused-vars
        localStorage.removeItem('googleAnalyticsConsent');
    ...
        return false;
      },
    
    
      /**
       * Initializes feature Google Analytics
       * Supposed to run after poageload, callback for $( () => { ... } );
       */
      init: function() { 
        this.resetConsent();
        ...
      },
    };

    Alternatively:

    const featureGoogleAnalytics = {
      gTagId: 'G-XXXXXXX', // Your Google Analytics ID
    
    ...
    
      resetConsent() { // eslint-disable-line no-unused-vars
        localStorage.removeItem('googleAnalyticsConsent');
    ...
        return false;
      },
    
    
      /**
       * Initializes feature Google Analytics
       * Supposed to run after poageload, callback for $( () => { ... } );
       */
      init() { 
        this.resetConsent();
        ...
      },
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search