在调用通过构造函数传入的函数时,我可以避免在Typescript中使用"this"这个词吗?

6 javascript angularjs typescript

我有:

class AdminHomeController {

    private config1; // I tried different variations here but none worked
    public config2;  //

    constructor(
                 private $scope: IAdminHomeControllerScope
               ) {
                     this.config = $scope.config; // << this works
                 }

    static $inject = [
        '$scope'
    ];

    configChanged = (clear) => {
        this.config.clear();
    };

}
Run Code Online (Sandbox Code Playgroud)

此代码有效并this.config具有我需要的所有方法.但有没有办法可以消除对此的需求this?我希望能够做的是编写以下代码:

configChanged = (clear) => {
    config.clear();
};
Run Code Online (Sandbox Code Playgroud)

我试过很多不同的变化,但我不能让它工作.

以下是更改为Typescript之前相同代码的示例:

angular.module('admin')
    .controller('AdminHomeController', [
        '$http',
        '$q',
        '$scope',
        'utilityService',
        adminHomeController]);

function adminHomeController(
    $http,
    $q,
    $scope,
    utilityService
    ) {

    var app = $scope.app;
    var config = app.config;
    var home = this;
    var util = utilityService;

    home.autoSave = false;
    home.data = {};
    home.entityType = null;
    home.forms = { grid: null, modal: null };
    home.grid = { view: [], data: [] };
    home.modal = { visible: false };
    home.row = {};
    home.rowSelected = null;

    home.configChanged = function (clear) {
        config.put();
        if (clear) {
            home.grid.backup = [];
            home.grid.data = [];
        }
    };
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 3

正如杰奇林所说:

如果省略“this”,解释器将仅在本地、闭包和全局作用域中查找变量名,而不是实际查找对象属性

因此,您可以在 TypeScript 中通过将函数定义移动到构造函数的主体中(您可以在其中访问闭包$scope变量)来实现这一点。这里我们也关闭一下config,然后在函数中使用:

class AdminHomeController {

    configChanged: ()=>void; // Need to declare the function  

    constructor(private $scope: any) {
        var config = $scope.config;
        this.configChanged = ()=> { // And then assign it
            config.clear();
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,它并不优雅。您有函数定义+声明拆分。此外,构造函数主体变得不必要的沉重。

这不应该归咎于 TypeScript。这只是 JavaScript。