1

I am using jQuery Widget Factory in my project, and I am trying as much as possible to use ES6 syntax, including arrow functions.

So, how do I reference this inside the methods of of the widget?

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)

$.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.

Greeso
  • 7,544
  • 9
  • 51
  • 77

2 Answers2

1

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. 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).

Nate Levin
  • 918
  • 9
  • 22
1

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.

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.

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979