我正在一个有 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/