简体   繁体   English

ES6 箭头函数和 jQuery 小部件工厂

[英]ES6 Arrow Functions and jQuery Widget Factory

I am using jQuery Widget Factory in my project, and I am trying as much as possible to use ES6 syntax, including arrow functions.我在我的项目中使用jQuery Widget Factory ,我正在尝试尽可能多地使用 ES6 语法,包括箭头函数。

So, how do I reference this inside the methods of of the widget?那么,我如何在小部件的方法中引用this呢?

As a hypothetical example, I would like to convert this code作为一个假设的例子,我想转换这段代码

$.widget( "custom.colorize", {
  
  // default options
  options: {
    red: 255,
    green: 0,
    blue: 0
  },

  // The constructor
  _create: function() {

    this.options.green = 128;
  }
});

to this code (note that I changed the _create function to an arrow function, which will throw an error)到此代码(请注意,我将_create function 更改为箭头 function,这将引发错误)

$.widget( "custom.colorize", {
  
  // default options
  options: {
    red: 255,
    green: 0,
    blue: 0
  },

  // The constructor
  _create: () => {

    this.options.green = 128;
  }
});

So, how can I reference the local variables as this is now not pointing to them?那么,我如何引用局部变量,因为它现在不指向它们?

Thanks.谢谢。

It looks like the jquery widget factory doesn't pass in the element in any other way, so you can just use regular anonymous function syntax.看起来 jquery 小部件工厂没有以任何其他方式传入元素,因此您可以使用常规的匿名 function 语法。 Note that the regular syntax is not inherently worse, and because you need a this context your only option is the normal way ( since arrow functions can't have a this value binded ).请注意,常规语法本身并不糟糕,并且因为您需要this上下文,所以您唯一的选择是正常方式(因为箭头函数不能绑定this)。

Don't use an arrow function for a method that you want this to be your object or for a method where the caller is explicitly setting this to be something you need.不要将箭头 function 用于您希望this成为您的 object 的方法,也不要用于调用者明确将this设置为您需要的方法。

Arrow functions are not just syntax shortcuts.箭头函数不仅仅是语法快捷方式。 They change the value of this to be the lexical value of this when they execute so you should only use arrow functions when you want the new behavior for this or when you aren't using this at all.它们在执行时将this的值更改为this的词法值,因此您应该仅在需要this的新行为或根本不使用this时使用箭头函数。

In your case, you should use a regular function definition, not an arrow definition so that caller can appropriately pass you the value of this .在您的情况下,您应该使用常规的 function 定义,而不是箭头定义,以便调用者可以适当地将this的值传递给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM