Babel 7 这变成了 _this angularjs

Babel 7 this becomes _this angularjs

我正在使用 ES6AngularJSbabel-loader 7.1.4Webpack 3 制作应用程序。 在我创建服务文件之前一切正常:

这是我的服务:

'use strict';

module.exports = (ngModule) => {

    ngModule.service('$ui', () => {


        //#region Methods

        /*
        * Trigger windows resize function.
        * */
        this.reloadWindowSize = () => {
            $(window).resize();
        };

        //#endregion
    });
};

将源代码从 ES6 转码到 ES2015 后,我的服务变成了:

module.exports = function (ngModule) {

    ngModule.service('$ui', function () {

        //#region Methods

        /*
        * Trigger windows resize function.
        * */
        _this.reloadWindowSize = function () {
            $(window).resize();
        };

        //#endregion
    });
};

如您所见,this现在变成了_this,因此,我无法执行服务文件中的功能。

这是我的babel配置

{
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: [['env', { "modules": false }]]
        }
    }
}

我做错了什么?

有人能帮帮我吗?

谢谢,

看完。我找到了答案。

我更改了我的服务实现:

'use strict';

module.exports = (ngModule) => {

    ngModule.service('$ui', () => {


        //#region Methods

        /*
        * Trigger windows resize function.
        * */
        this.reloadWindowSize = () => {
            $(window).resize();
        };

        //#endregion
    });
};

为此:

module.exports = (ngModule) => {

    ngModule.service('$ui', () => {

        return {

            //#region Methods

            /*
            * Reload window size.
            * */
            reloadWindowSize: () => {
                $(window).resize();
            }

            //#endregion
        }
    });
};

在服务声明中,我 return 一组函数并且它起作用了。

只是想让任何人知道这件事。找了一个晚上才找到答案

箭头函数不仅仅是常规函数的快捷方式。

the reference所述,

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

由于源代码包含多个嵌套箭头函数,this 是通过 _this 变量从顶层范围检索的,即 undefined,因为它是模块范围,并且是严格模式已启用。

service 服务使用箭头函数在语义上是不正确的,因为它们是用 new 实例化并使用 this 作为服务实例,而箭头不能 new ed 并且没有自己的 this.

应该是:

ngModule.service('$ui', function () {
    //#region Methods

    /*
    * Trigger windows resize function.
    * */
    this.reloadWindowSize = () => {
        $(window).resize();
    };

    //#endregion
});