代码之家  ›  专栏  ›  技术社区  ›  Douglas Gaskell

有棱角的js:Typescript类构造函数“这是未定义的”

  •  6
  • Douglas Gaskell  · 技术社区  · 7 年前

    我试图创建一个简单的TypeScript类,但是当它被实例化时,我收到一个 this is undefined 构造函数中存在错误。

    类别:

    class MyClass {
        stuff: string;
        constructor(){
            this.stuff = 'stuff';
        }
    }
    app.config([MyClass]);
    

    编译为:

    var MyClass = /** @class */ (function () {
        function MyClass() {
            this.stuff = 'stuff';
        }
        return MyClass;
    }());
    app_module_1.app.config([MyClass]);
    

    为什么这不起作用?为什么是 this 未定义?基于我编写的示例和其他代码,这似乎是合适的语法。

    我代码的其余部分(有效):

    export let app = angular.module('timeApp', [
        uirouter
    ]);
    
    class MainController{
        stuff: string;
        constructor(){
            this.stuff = "TESTING";
        }
    }
    
    app.controller('mainController', MainController);
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   basarat    7 年前

    为什么这不起作用?

    因为你正在使用 app.config([MyClass]); Angular将称之为无 new 因此 this 将未定义

    修理

    不要使用带有角度的类 config . 使用函数。

    更多