How can I preserve lexical scope in TypeScript wit

2019-01-08 10:40发布

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 object
    // I must use '_this' to get the class itself
    ...
}

I pass it in to another function

this.deleteRow(this.removeRow);

which in turn calls a jQuery Ajax method, which if successful, invokes the callback like this:

deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })
    .done(() => {
        removeRowCallback(this);
    })
    .fail(() => {
        alert("There was an error!");
    });
}

The only way I can preserve the 'this' reference to my class is to pass it on to the callback, as demonstrated above. It works, but it's pants code. If I don't wire up the 'this' like this (sorry), then any reference to this in the callback method has reverted to the Window object. Because I'm using arrow functions all the way, I expected that the 'this' would be the class itself, as it is elsewhere in my class.

Anyone know how to pass callbacks around in TypeScript, preserving lexical scope?

5条回答
forever°为你锁心
2楼-- · 2019-01-08 11:17

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. :)

查看更多
闹够了就滚
3楼-- · 2019-01-08 11:19

UPDATE: See Sly's updated answer. It incorporates an improved version of the options below.

ANOTHER UPDATE: Generics

Sometimes you want to specify a generic type in a function signature without having to specify it on the the whole class. It took me a few tries to figure out the syntax, so I thought it might be worth sharing:

class MyClass {  //no type parameter necessary here

     public myGenericMethod = <T>(someArg:string): QPromise<T> => {

         //implementation here...

     }
}

Option 4

Here are a couple more syntaxes to add to Sly_cardinal's answer. These examples keep the function declaration and implementation in the same place:

class Test {

      // Define the method signature AND IMPLEMENTATION here.
      public removeRow: () => void = () => {

        // Perform your logic to remove the row.
        // Reference `this` as needed.

      }

      constructor (){

      }

}

or

Option 5

A little more compact, but gives up explicit return type (the compiler should infer the return type anyway if not explicit):

class Test {

      // Define implementation with implicit signature and correct lexical scope.
      public removeRow = () => {

        // Perform your logic to remove the row.
        // Reference `this` as needed.

      }

      constructor (){

      }

}

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-08 11:24

Use .bind() to preserve context within the callback.

Working code example:

window.addEventListener(
  "resize",
  (()=>{this.retrieveDimensionsFromElement();}).bind(this)
)

The code in original question would become something like this:

$.ajax(action, {
    data: { "id": id },
    type: "POST"
})
.done(
  (() => {
    removeRowCallback();
  }).bind(this)
)

It will set the context (this) inside the callback function to whatever was passed as an argument to bind function, in this case the original this object.

查看更多
女痞
5楼-- · 2019-01-08 11:25

Edit 2014-01-28:

New readers, make sure you check out Zac's answer below.

He has a much neater solution that will let you define and instantiate a scoped function in the class definition using the fat arrow syntax.

The only thing I will add is that, in regard to option 5 in Zac's answer, it's possible to specify the method signature and return type without any repetition using this syntax:

public myMethod = (prop1: number): string => {
    return 'asdf';
}

Edit 2013-05-28:

The syntax for defining a function property type has changed (since TypeScript version 0.8).

Previously you would define a function type like this:

class Test {
   removeRow: (): void;
}

This has now changed to:

class Test {
   removeRow: () => void;
}

I have updated my answer below to include this new change.

As a further aside: If you need to define multiple function signatures for the same function name (e.g. runtime function overloading) then you can use the object map notation (this is used extensively in the jQuery descriptor file):

class Test {
    removeRow: {
        (): void;
        (param: string): string;
    };
}

You need to define the signature for removeRow() as a property on your class but assign the implementation in the constructor.

There are a few different ways you can do this.

Option 1

class Test {

    // Define the method signature here.
    removeRow: () => void;

    constructor (){
        // Implement the method using the fat arrow syntax.
        this.removeRow = () => {
            // Perform your logic to remove the row.
            // Reference `this` as needed.
        }
    }

}

If you want to keep your constructor minimal then you can just keep the removeRow method in the class definition and just assign a proxy function in the constructor:

Option 2

class Test {

    // Again, define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Assign the method implementation here.
        this.removeRowProxy = () => {
            this.removeRow.apply(this, arguments);
        }
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

Option 3

And finally, if you're using a library like underscore or jQuery then you can just use their utility method to create the proxy:

class Test {

    // Define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Use jQuery to bind removeRow to this instance.
        this.removeRowProxy = $.proxy(this.removeRow, this);
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

Then you can tidy up your deleteItem method a bit:

// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })

    // Pass the callback here.
    // 
    // You don't need the fat arrow syntax here
    // because the callback has already been bound
    // to the correct scope.
    .done(removeRowCallback)

    .fail(() => {
        alert("There was an error!");
    });
}
查看更多
贼婆χ
6楼-- · 2019-01-08 11:29

This is sort of a cross post from another answer (Is there an alias for 'this' in TypeScript?). I re-applied the concept using the examples from above. I like it better than the options above because it explictly supports "this" scoping to both the class instance as well as the dynamic context entity that calls the method.

There are two versions below. I like the first one because the compiler assists in using it correctly (you won't as easily try to misuse the callback lambda itself as the callback, because of the explicitly typed parameter).

Test it out: http://www.typescriptlang.org/Playground/

class Test {

    private testString: string = "Fancy this!";

    // Define the method signature here.
    removeRowLambdaCallback(outerThis: Test): {(): void} {
        alert("Defining callback for consumption");
        return function(){
            alert(outerThis.testString); // lexically scoped class instance
            alert(this); // dynamically scoped context caller
            // Put logic here for removing rows. Can refer to class
            // instance as well as "this" passed by a library such as JQuery or D3.
        }
    }
    // This approach looks nicer, but is more dangerous
    // because someone might use this method itself, rather
    // than the return value, as a callback.
     anotherRemoveRowLambdaCallback(): {(): void} {
        var outerThis = this;
        alert("Defining another callback for consumption");
        return function(){
            alert(outerThis.testString); // lexically scoped class instance
            alert(this); // dynamically scoped context caller
            // Put logic here for removing rows. Can refer to class
            // instance as well as "this" passed by a library such as JQuery or D3.
        }
    }
}

var t = new Test();
var callback1 = t.removeRowLambdaCallback(t);
var callback2 = t.anotherRemoveRowLambdaCallback();

callback1();
callback2();
查看更多
登录 后发表回答