Gulp-Uglify: $(void 0) when caching DOM

Gulp-Uglify: $(void 0) when caching DOM

当使用 gulp-uglify 和缓存 DOM 元素(使用 jQuery)时,uglify 从 $(this).[=16= 中生成 $(void 0) ]

$(document).on("click", "sth", () => {
    var $this = $(this);
    ...
});

会产生这样的结果:

$(document).on("click", "sth", function() {
    var e = $(void 0);
    ...
});

我怎样才能避免这种情况?

箭头函数do not bind this:

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.

这意味着 this 在您的示例中指的是周围范围的 this 。由于您的箭头函数不在另一个函数内,因此 this 指的是全局 this.

在浏览器中全局 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 。在 ES6 模块中,this 的值是 undefined.

这意味着 babel() 将转换此代码:

var $this = $(this);

进入此代码:

var $this = $(undefined);

接下来是 uglify(),它试图尽可能地压缩上面的行。为此,它利用了 void 0 evaluates to undefined 并且由于 void 0undefined 短的事实,你最终得到了这个:

var e = $(void 0);

你如何解决这个问题?简单。不要使用箭头函数:

$(document).on("click", "sth", function() {
    var $this = $(this);
    ...
});