How can I preserve lexical scope in TypeScript with a callback function

前端 未结 5 2094
小蘑菇
小蘑菇 2020-11-29 01:01

I have a TypeScript class, with a function that I intend to use as a callback:

removeRow(_this:MyClass): void {
    ...
    // \'this\' is now the window obj         


        
5条回答
  •  孤街浪徒
    2020-11-29 01:33

    Building upon sly and Zac's answers with types: A complete hello world example. I hope this is welcome, seeing as this is the top result in Google, when searching for "typescript javascript callbacks"

    type MyCallback = () => string;
    
    class HelloWorld {
    
        // The callback
        public callback: MyCallback = () => {
            return 'world';
        }
    
        // The caller
        public caller(callback: MyCallback) {
            alert('Hello ' + callback());
        }
    }
    
    let hello = new HelloWorld();
    hello.caller(hello.callback);
    

    This gets transpiled into:

    var HelloWorld = (function () {
        function HelloWorld() {
            // The callback
            this.callback = function () {
                return 'world';
            };
        }
        // The caller
        HelloWorld.prototype.caller = function (callback) {
            alert('Hello ' + callback());
        };
        return HelloWorld;
    }());
    var hello = new HelloWorld();
    hello.caller(hello.callback);
    

    Hope someone finds it just a little useful. :)

提交回复
热议问题