AngularJS 提供者不接受 ES6 函数声明

AngularJS Provider doesn't accept ES6 function declaration

我一直在尝试重写我们的一些代码以符合 ES6,但遇到了以下问题。

angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:pget] Provider 'books' must define $get factory method.

这是我在这段代码中写provider对象的时候。

(() => {
    const app = angular.module('app', []);

    const books = () => { // Error is here
        let includeVersionInTitle = false;

        this.$get = () => {
            const appName = "Book Logger";
            const appDesc = "Track which books you read.";
            let version = "1.0";

            appName = (includeVersionInTitle) ? (appName += " " + version) : appName;

            return {
                appName: appName,
                appDesc: appDesc
            }
        };

        this.setIncludeVersionInTitle = (value) => {
            includeVersionInTitle = value;
        };
    };

    app.provider("books", [books]);
})();

当我把const books = () => { ... }改成这个的时候,const books = function() { ... }。它会工作并且不会抛出该错误。

我还以为const a = function() { ... }const a = () => { ... }是一回事?为什么会抛出这个错误?

箭头函数没有自己的 "this",而是使用周围代码的函数。您必须使用传统函数。

this.$get = function() {

您可以在此处查看更深入的解释:

https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/