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

标签 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();
    };

}

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

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

我尝试了许多不同的变体,但我无法让它工作。

这是更改为 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 = [];
        }
    };

最佳答案

正如 djechilin 所说:

If you omit "this," the interpreter will simply look for the variable name in local, closured and global scopes, not actually look up object properties

因此,您可以在 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();
        };
    }
}

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

TypeScript 并不是罪魁祸首。这只是 JavaScript。

关于javascript - 调用通过构造函数传入的函数时,我可以避免在 Typescript 中使用单词 "this"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24977814/

相关文章:

javascript - 在 TinyMCE 编辑器中使用自定义 Angular 属性

javascript - ng-click 的奇怪错误

javascript - Angularfire firebase 身份验证 - 谷歌

javascript - 嵌套 Map 为空的 POST 请求

node.js - 找不到名称 'process' Angular 5

javascript - 在 TypeScript 中重构单页 Web 应用程序

javascript - 验证码错误 400

javascript - jQuery Autocomplete 快完成了吗?

javascript - 如何使用 npm 更新特定的子包版本

javascript - AngularJS:在接收内容之前渲染表格列