typescript 在打字稿中绑定函数和 this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34499583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:10:55  来源:igfitidea点击:

bind function and this in typescript

javascripttypescript

提问by Seb Bizeul

I wanted to implement a simple context binding but it doesn't work in TypeScript. Here is my piece of code:

我想实现一个简单的上下文绑定,但它在 TypeScript 中不起作用。这是我的一段代码:

class Engine {
    // some code...

    spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
        callbackfn.bind(new SpriteController(sprite), [this._ctx]);
    }

    // code again ...
}

If I want to use spriteController method in another file like this:

如果我想在另一个文件中使用 spriteController 方法,如下所示:

engine.spriteController(sprite, function(ctx) {
    this.moveRight() // access to the spriteController class
})

I want to be able to use the SpriteController class within the callback.
In JS, the first argument (within the bind() call) bind 'this' to the given object. But in TypeScript, functions created from function.bind are always preserve 'this'.
How to achieve this in TypeScript?

我希望能够在回调中使用 SpriteController 类。
在 JS 中,第一个参数(在 bind() 调用中)将“this”绑定到给定的对象。但是在 TypeScript 中,从 function.bind 创建的函数总是保留“this”。
如何在 TypeScript 中实现这一点?

回答by CoderPi

When binding, it is returning the bound function, you have to update your variable width callbackfn = callbackfn.bind(...):

绑定时,它返回绑定函数,您必须更新变量 width callbackfn = callbackfn.bind(...)

Documentation link

文档链接

class Engine {
    spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
        let callbackfnBinded = callbackfn.bind(new SpriteController(sprite), [this._ctx])
        callbackfnBinded()
    }
}

JavaScript here:

这里的 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);