我想实现一个简单的上下文绑定,但是在TypeScript中不起作用。这是我的代码:
class Engine {
// some code...
spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
callbackfn.bind(new SpriteController(sprite), [this._ctx]);
}
// code again ...
}
如果我想在另一个文件中使用spriteController方法,例如:
engine.spriteController(sprite, function(ctx) {
this.moveRight() // access to the spriteController class
})
我希望能够在回调中使用SpriteController类。
在JS中,第一个参数(在bind()调用内)将'this'绑定到给定的对象。但是在TypeScript中,从function.bind创建的函数始终保留“ this”。
如何在TypeScript中实现呢?
绑定时,它返回绑定函数,您必须更新变量width callbackfn = callbackfn.bind(...)
:
class Engine {
spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
let callbackfnBinded = callbackfn.bind(new SpriteController(sprite), [this._ctx])
callbackfnBinded()
}
}
JavaScript在这里:
var Sprite = (function () {
function Sprite(name) {
this.name = name;
}
return Sprite;
})();
var SpriteController = (function () {
function SpriteController(sprite) {
this.sprite = sprite;
}
return SpriteController;
})();
var Engine = (function () {
function Engine() {
}
Engine.prototype.spriteController = function (sprite, callbackfn) {
callbackfn = callbackfn.bind(new SpriteController(sprite), [this._ctx])
callbackfn()
};
return Engine;
})();
var e = new Engine();
var s = new Sprite("test");
var cb = function (ctx) {
alert(this.sprite.name);
};
e.spriteController(s, cb);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句