简体   繁体   中英

Missing _this definition

I have a function defined in a object like this:

    connect(callback?: (connected: bool) => void) {
        $.ajax(this.url + "/connect", $.extend(true, {}, this.ajaxSettings, {
            success: (data) => {
                this.errorChecker(data, (data) => {
                    if (callback != null) {
                        callback(data);
                    }
                });
            },
            timeout: this.timeout,
            error: () => {
                if (callback != null) {
                    callback(false);
                }
            }
        }));
    }

The TypeScript compiler takes that and produces this:

        VAS.prototype.connect = function (callback) {
            $.ajax(this.url + "/connect", $.extend(true, {
            }, this.ajaxSettings, {
                success: function (data) {
                    _this.errorChecker(data, function (data) {
                        if(callback != null) {
                            callback(data);
                        }
                    });
                },
                timeout: this.timeout,
                error: function () {
                    if(callback != null) {
                        callback(false);
                    }
                }
            }));
        };

Note this line in the js:

_this.errorChecker(data, function (data)

The compiler has correctly noticed my use of the => operator and concluded that this in my original TypeScript should refer to the parent object and not whatever this happens to be when the success callback is actually called. But, for some reason the compiler has forgotten to include the magic line:

var _this = this;

At the start of the function. Is this a bug? Or is this by design? If it just ignored the _this / this thing altogether, I'd just say I'm doing it wrong, but it's going half way here which makes me think something is wrong.

Update : oddly this seems to be a problem with the compiler in Visual Studio, if I copy the same code into the playground it works as expected.

This looks like a bug. You should open a work item to track this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM