【问题标题】:How to write non-arrow function as argument如何编写非箭头函数作为参数
【发布时间】:2021-01-18 14:52:06
【问题描述】:

是的,我已经知道 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,我想要做的只是访问 debounce 函数中的 this 属性,因为它与外部范围(一个 Vue 实现细节)有关。问题显然是箭头函数。

我找不到正确的语法。我用() { }尝试了所有我能想到的排列方式

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

我如何在 ES6 中直接编写它,以便我可以访问 this

【问题讨论】:

  • debounce(function(event) {
  • @JaromandaX 当我这样做 ESLint 投诉时。我正在尝试找到他们为“当前标准”推荐它的方式
  • 这不是关于绕过箭头函数的问题,这是关于绑定函数的问题!
  • 你试过function somename() { }吗?
  • @tony19 - 完成 - 你说服了我:p

标签: javascript vue.js ecmascript-6 vuejs3


【解决方案1】:

我不是 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
   }
  }
}

【讨论】:

  • 嘿,debounce 是我正在导入的一个库,它返回一个函数(目的是去抖动它)
【解决方案2】:

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

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

命名此类函数的目的纯粹是出于调试目的 - 错误堆栈跟踪将包含该函数的名称,而不是 anonymous function(或类似名称),如果您有一个大型代码库且有很多人在工作,这将很有用它

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

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

【讨论】:

    猜你喜欢
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2015-03-14
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    相关资源
    最近更新 更多