When using gulp-uglify and caching DOM elements (with jQuery), uglify makes $(void 0)
out of $(this)
.
$(document).on("click", "sth", () => {
var $this = $(this);
...
});
Will result in this:
$(document).on("click", "sth", function() {
var e = $(void 0);
...
});
How can I prevent this?
Arrow functions do not bind this
:
An arrow function does not create its own this context, so
this
has its original meaning from the enclosing context.
That means this
in your example refers to the this
of the surrounding scope. Since your arrow function is not inside another function, the this
refers to the global this
.
In a browser the global this
refers to the window
object. However I'm guessing you're using babel
with the babel-preset-es2015
preset. In this case babel
will assume that your code is inside an ES6 module. Inside an ES6 module the value of this
is undefined
.
That means babel()
will transpile this code:
var $this = $(this);
Into this code:
var $this = $(undefined);
Next up you have uglify()
, which tries to compress the above line as much as possible. To this end it exploits the fact that void 0
evaluates to undefined
and since void 0
is shorter than undefined
you end up with this:
var e = $(void 0);
How do you fix this? Easy. Don't use an arrow function:
$(document).on("click", "sth", function() {
var $this = $(this);
...
});