如何编写非箭头函数作为参数

How to write non-arrow function as argument

是的,我已经知道 9028924 人会在发布后 8 秒内将其标记为重复问题。相信我...我已经用谷歌搜索了将近一个小时,否则我不会问。

  methods: {
    stylizeHeader: debounce(event => {
      if (event.target.scrollTop <= 1 && !this.scrolled) {
        this.scrolled = true;
        console.log('true');
      } else if (this.scrolled) {
        this.scrolled = false;
        console.log('false');
      }
    }, 20),
  },

我正在使用 Vue,我想做的就是访问去抖函数中的 this 属性,因为它与外部作用域相关(Vue 实现细节)。很明显是箭头函数的问题

我找不到正确的语法。我已经用 () { }

尝试了所有我能想到的排列

如果我使用 function() { } 它工作正常,但 eslint 抱怨(所以我想遵循良好的最新约定)。

我如何直接用 ES6 编写它以便我可以访问 this

如果 function() {} 有效,但 linter 抱怨函数没有名称,那么只需给函数一个名称

methods: {
  stylizeHeader: debounce(function debouncedStylizeHeader(event) {
    // ..... your code
  }, 20),
},

命名此类函数的目的纯粹是为了调试目的 - 错误堆栈跟踪将包含该函数的名称,而不是 anonymous function(或类似名称),如果您的代码库很大许多人在努力

也许您使用的 linter 规则是为这样的环境(即大型代码库)设计的,并且该规则可以帮助调试错误

没有理由不这样做,这是很好的做法(在我看来)

我不是 Vuejs 开发人员,但我使用 vanilla JavaScript 和 NodeJS。

虽然我在努力理解您的代码,但我想这就是您要编写的内容。 您的函数似乎有两个名称:stylizeHeader: denounce。然而,Vue 的方法部分接受的函数并不是真正的对象类型的定义。您必须选择一个名称。

试试这个改变这个

  methods: {
    stylizeHeader: debounce(event => {
      if (event.target.scrollTop <= 1 && !this.scrolled) {
        this.scrolled = true;
        console.log('true');
      } else if (this.scrolled) {
        this.scrolled = false;
        console.log('false');
      }
    }, 20),
  },

  methods: {
    stylizeHeader (event) {
    // You can now set timer/interval here 
    // which in turn will hold rest of the code below
      if (event.target.scrollTop <= 1 && !this.scrolled) {
        this.scrolled = true;
        console.log('true');
      } else if (this.scrolled) {
        this.scrolled = false;
        console.log('false');
      }
    },
  },

  methods: {
    debounce (event) {
    // You can now set timer/interval here 
    // which in turn will hold rest of the code below
      if (event.target.scrollTop <= 1 && !this.scrolled) {
        this.scrolled = true;
        console.log('true');
      } else if (this.scrolled) {
        this.scrolled = false;
        console.log('false');
      }
    },
  },

但是,如果您的实现是闭包,为什么不这样做:

 methods: {
  stylizeHeader (event) {
   debounce() {
    //code
   }
  }
}