$ .ajax()中"this"关键字的TypeScript解释

Kla*_*Nji 5 intellisense typescript

我意识到TypeScript编译器试图保持对普通旧JavaScript的忠诚,因为TypeScript确实是JavaScript.然而,Intellisense解释为"this"关键字与它在运行时实际解析的内容之间存在脱节.例如,考虑以下TypeScript ajax调用:

 getAgencies() {
            var self = this;          
            $.ajax(liveString + "/Home/GetSupportedAgencies",
            {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: Utilities.Logger.displayAjaxError,
                success: this.onGetAgenciesComplete
            });

        }
Run Code Online (Sandbox Code Playgroud)

及其相应的回调:

   onGetAgenciesComplete(agencies) {
                var self = this;
                    if (agencies == null)
                        Utilities.Logger.displayErrorOnLogConsole("There was an error retrieving supported agencies.  Refresh site and try again.");
                    else {
                        $.each(agencies, function (i, a) {
                            self._indexViewModel.agencies.push({ name: a.Name, fullName: a.FullName, shortName: a.ShortName, bbox: a.BBox, countryCode: a.CountryCode });
                        });

                        if (Modernizr.geolocation) {
                            navigator.geolocation.getCurrentPosition(
                                function (position) {
                                    self.initMapPage(position, self);
                                },
                                function (error) {
                                    Utilities.Logger.displayErrorOnLogConsole("Oops, we could not get your location at his time. Please try later.");
                                });
                        }
                        else {
                            Utilities.Logger.displayErrorOnLogConsole("Sorry, your browser does not return location information.");
                            self.getBusRoutes(self.agencyName);
                        }


                        // end of initialization
                    }
                }
Run Code Online (Sandbox Code Playgroud)

现在,当我将鼠标悬停在TypeScript源文件中的onGetAgenciesComplete上的"var self = this"行时,变量"self"的Intellisense定义表明它是HomePageViewModelBase类型,其中HomePageViewModelBase是包含上述方法的类.

上面生成的Javascript如下:

HomePageViewModelBase.prototype.getAgencies = function () {
            var self = this;
            $.ajax(liveString + "/Home/GetSupportedAgencies", {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: Utilities.Logger.displayAjaxError,
                success: this.onGetAgenciesComplete
            });
        };
        HomePageViewModelBase.prototype.onGetAgenciesComplete = function (agencies) {
            var self = this;
            if(agencies == null) {
                Utilities.Logger.displayErrorOnLogConsole("There was an error retrieving supported agencies.  Refresh site and try again.");
            } else {
                $.each(agencies, function (i, a) {
                    self._indexViewModel.agencies.push({
                        name: a.Name,
                        fullName: a.FullName,
                        shortName: a.ShortName,
                        bbox: a.BBox,
                        countryCode: a.CountryCode
                    });
                });
                if(Modernizr.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        self.initMapPage(position, self);
                    }, function (error) {
                        Utilities.Logger.displayErrorOnLogConsole("Oops, we could not get your location at his time. Please try later.");
                    });
                } else {
                    Utilities.Logger.displayErrorOnLogConsole("Sorry, your browser does not return location information.");
                    self.getBusRoutes(self.agencyName);
                }
            }
        };
Run Code Online (Sandbox Code Playgroud)

当在HomePageViewModelBase.prototype.onGetAgenciesComplete中执行变量"self"时,将解析为看起来像AjaxContext而不是HomePageViewModelBase的实例.这是预期的行为,还是应该将此报告为错误?

Mar*_*.io 6

是的,您应该将它作为一个错误报告给它们,因为其中this的内容$.ajax()是指$.ajax()对象本身.

如果您想绕过它以便它可以工作,请将您的成功功能更改为:

success: self.onGetAgenciesComplete
Run Code Online (Sandbox Code Playgroud)

或者,如果你this静置类,只需使用上下文的$就法

$.ajax({ 
    context: this,
    // now *this* will come from the previous scope,
    // which in your case, is your class "HomePageViewModelBase"

    // now that we know for certain what -this- refers to
    success: this.onGetAgenciesComplete
});
Run Code Online (Sandbox Code Playgroud)