从对象文字符号内的另一个箭头函数调用箭头函数[重复]

问题描述 投票:0回答:2

我想使用对象文字表示法来生成命名空间:

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();
    ...
  },
};

现在线路

this.resetConsent();

错误

Uncaught TypeError: this.resetConsent is not a function

我错过了什么?我认为调用

resetConsent
函数的语法是错误的,但我无法通过 Google 搜索它。

javascript ecmascript-6
2个回答
0
投票

语法是:

featureGoogleAnalytics.resetConsent();


0
投票

根据注释,不要在对象定义中使用匿名函数包装器。

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();
    ...
  },
};

或者:

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();
    ...
  },
};

© www.soinside.com 2019 - 2024. All rights reserved.