Randall Flagg
Randall Flagg

Reputation: 5108

TypeScript output difference with lambda functions and normal functions

I have this code:

var initChannelEvents = () =>
    $("#channels a").click(
        (eventObject: JQueryEventObject) => setActiveChannel(this)
    );

And this:

var initChannelEvents2 = () =>
    $("#channels a").click(
        function (eventObject: JQueryEventObject) {
            setActiveChannel(this);
        });

The output is:

var _this = this;
var initChannelEvents = function () {
    return $("#channels a").click(function (eventObject) { 
        return setActiveChannel(_this); });
    };

and this:

var initChannelEvents2 = function () {
    return $("#channels a").click(function (eventObject) {
        setActiveChannel(this);
    });
};

UPDATE:

TS:

var initChannelEvents2 = () =>
    $("#channels a").click(
        (eventObject: JQueryEventObject) => {
            setActiveChannel(this);
        }
    );

JS:

var _this = this;
var initChannelEvents2 = function () {
    return $("#channels a").click(function (eventObject) {
        setActiveChannel(_this);
    });
};

I understand the output of the second snippet and that is what I expected. I don't understand the output of the first. I would expect them to be the same.

Why are they different? What am I not understanding here?

Upvotes: 2

Views: 322

Answers (1)

Lambda/arrow functions (() => ...) in TypeScript (and in JavaScript ES6) have some additional behaviour beyond standard function expressions, requiring some additional code when compiling to JavaScript ES3/ES5.

var _this = this;

The value of this within the lambda is automatically bound/saved to the value of this outside of the lambda. A normal function would get its value for this based on how it's called.

return setActiveChannel(_this);

If the body of a lambda function is a single expression (not a block { ... }), the value of that expression will be automatically returned, without an explicit return statement.

Upvotes: 2

Related Questions