Javascript &引用;这";在Typescript类实例中
在javascript中,我可以使用savingthis来实现作用域\u this,或者直接将函数绑定到this(function.bind或下划线js绑定实用程序) 但是typescript应该更面向对象,我希望typescript中的这个指向类实例。但它的工作原理与JS中的一样。所以我必须使用构造Javascript &引用;这";在Typescript类实例中,javascript,this,typescript,Javascript,This,Typescript,在javascript中,我可以使用savingthis来实现作用域\u this,或者直接将函数绑定到this(function.bind或下划线js绑定实用程序) 但是typescript应该更面向对象,我希望typescript中的这个指向类实例。但它的工作原理与JS中的一样。所以我必须使用构造 export class Mouse { private board : Presentation.View.Board; private focus :
export class Mouse {
private board : Presentation.View.Board;
private focus : Presentation.View.Element = null;
constructor(board:Presentation.View.Board){
var _this = this;
board.bindMouse(
function(event:JQueryEventObject){
if( _this.focus ) _this.focus.move(event);
}
);
}
或
所以我问,有没有办法避免这种直接的微观管理?我想有一种方法可以实现某种占卜,这样类实例总是有一些对自身的引用(它可以有任何名称,比如,。使用箭头函数。形成规范: 使用function关键字的函数表达式将引入一个新的动态绑定, 而arrow函数表达式保留了它的封闭上下文。 箭头函数表达式对于编写回调特别有用,否则回调通常
有一个未定义的或意外的
我真的不喜欢这种C-type语法,但看起来它是唯一的好选择。这很奇怪,因为我知道大多数开发人员都喜欢arrow语法。
export class Mouse {
private board : Presentation.View.Board;
private focus : Presentation.View.Element = null;
constructor(board:Presentation.View.Board){
var _this = this;
board.bindMouse(
_.bind(function(event:JQueryEventObject){
if( this.focus ) this.focus.move(event);
}, this);
);
}
board.bindMouse((event: JQueryEventObject) => {
if(this.focus) this.focus.move(event);
});