angularjs - Angular 和 Typescript : proper way to reference 'this'

标签 angularjs typescript controller

我正在一个有 Angular 的项目中设置 typescript 。为了声明 Controller ,我使用以下语法:

module app {

    class MyController {
        public myvar: boolean;

        constructor() {
            this.myvar= false;
        }
    }
    angular.module("app").controller("MainController", [MainController]);
}

请注意,我不注入(inject)范围,我只使用 Controller 的内部属性/方法。 但我不喜欢用“this”访问属性,通常我应该声明:

var vm = this.
vm.myvar = ...

但是这很烦人,因为我有很多方法;我应该在任何人中声明这一点,这是重复的。

是否有最佳实践和/或模式,以便仅声明“vm”一次?

最佳答案

But I don't like to access to properties with 'this', usually I should declare var vm = this ... Is there a best practice and/or a pattern, in order to declare the 'vm' only once?

现在是放弃这种做法的好时机。在 TypeScript 中,很容易只使用 this,而不将 this 分配给变量 - 它已经为您定义了,所以使用它很不错。

执行此操作的关键是使用箭头函数来确保始终使用类实例的 this 而不是绑定(bind)到正则函数表达式的 this

class MyController {
    myVar = false;

    someOtherMethod() {
        // good
        functionWithCallback(() => {
            // this will be the class instance
            console.log(this.myVar);
        });

        // bad
        functionWithCallback(function() {
            // this will not be the class instance
            console.log(this.myVar);
        });

        // good
        functionWithCallback(() => this.myOtherMethod());

        // bad, `this` in myOtherMethod is not the class instance
        functionWithCallback(this.myOtherMethod);
    }

    myOtherMethod() {
        console.log(this.myVar);
    }
}

function functionWithCallback(callback: Function) {
    callback();
}

关于angularjs - Angular 和 Typescript : proper way to reference 'this' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37485153/

相关文章:

ruby - rspec Controller 操作后测试失败,并出现 ActiveModel::ForbiddenAttributesError

javascript - Angular.js 和 chrome 应用程序的最佳缓存策略是什么?

javascript - Angular UI Router - 嵌套路由不适用于具有嵌套状态的模板

javascript - 将焦点设置在 Angular 中父组件的子组件文本框上

typescript - React-leaflet:默认标记在缩放时移动

javascript - marionette.js Controller 初始化中的 this.options 参数

asp.net - 将 int 数组发布到 MVC Controller - 正确的方法签名是什么?

node.js - Angular 速度未捕获错误 : [$injector:modulerr]

javascript - ng-repeat 每三次重复换行

visual-studio - 如何在 Visual Studio 2015 中使用 TypeScript 创建通用 Windows 应用程序?