Javascript 无法获取未定义或空引用的属性 - Windows 8 JS/CSS 应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14210765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:02:19  来源:igfitidea点击:

Unable to get property of undefined or null reference - Windows 8 JS/CSS app

javascriptwindows-8

提问by James

Below is a snippet of my code. The error I am getting is that when I perform a search and call the method _searchData, it successfully calls the method _lookUpSuccess, however then returns the following error:

下面是我的代码片段。我得到的错误是,当我执行搜索并调用方法时_searchData,它成功调用了方法_lookUpSuccess,但随后返回以下错误:

JavaScript runtime error: Unable to get property '_displayResult' of undefined or null reference

JavaScript 运行时错误:无法获取未定义或空引用的属性“_displayResult”

when it tries to call the _displayResultmethod.

当它尝试调用该_displayResult方法时。

Why this may be?

为什么会这样?

(function () {

    // make this an object property/method eventually
    var displayResult = function (queryResult) {
        for (var i = 0; i < holder.length; i++) {
            //document.querySelector(".item-content .title").textContent = "FilmApp";
            document.querySelector(holder[i]).textContent = queryResult[i];
       }};

    // Creates a new page control with members
    ui.Pages.define(searchPageURI, {
       //...
        _searchData: function (queryText) {
            searchBase          = 'http://www.example.com/web-service2.php?termID=';
            searchFormat        = 'JSON';
            searchFormatPiece   = '&format=' + searchFormat;

            if (!window.Data) {  
                var searchUrl = searchBase + queryText + searchFormatPiece;
                WinJS.xhr({ url: searchUrl }).done(this._lookUpSuccess, this._lookUpFail, this._lookUpProgress);
            }else{
                document.querySelector(".titlearea .pagetitle").textContent = "There has been a computer malfunction - sort it the **** out!";
            }
        },

        _lookUpSuccess: function xhrSucceed(Result) {
            var response = JSON.parse(Result.responseText);
                if (response.response[0].Message === "Found") {
                    for (var x in response.response[1].term) {
                        content.push(response.response[1].term[x]);
                    };
                    this._displayResult(content);
                    //displayResult(content);
                    return content;
                } else {
                    content.push("Not Found", "Not Found");
                    return content;
                }
         },

        _lookUpFail: function xhrFail(Result) { document.querySelector(".titlearea .pagetitle").textContent = "Got Error"; },
        _lookUpProgress: function xhrProgress(Result) { document.querySelector(".titlearea .pagetitle").textContent = "No Result 2"; },

        _displayResult: function (queryResult) {
            var holder;
            holder = [DefDiv, DescDiv];

            for (var i = 0; i < holder.length; i++) {
                //document.querySelector(".item-content .title").textContent = "FilmApp";
                document.querySelector(holder[i]).textContent = queryResult[i];
            };
        },

    });

    // End of UI.page.define    

    // #2 This method is run on application load
    WinJS.Application.addEventListener("activated", function (args) {
        if (args.detail.kind === appModel.Activation.ActivationKind.search) {
            args.setPromise(ui.processAll().then(function () {
                if (!nav.location) {
                    nav.history.current = { location: Application.navigator.home, initialState: {} };
                }
            return nav.navigate(searchPageURI, { queryText: args.detail.queryText });
            }));
        }
    });

    // #3 
    appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args) { nav.navigate(searchPageURI, args); };

})();

回答by jfriend00

In this line of code:

在这行代码中:

WinJS.xhr({ url: searchUrl }).done(this._lookUpSuccess, this._lookUpFail, this._lookUpProgress);

You are passing _lookupSuccessas the done handler function, but when it is called, the value of thisis no longer what you want it to be because that will be set by the internals of whatever calls the done handler. Passing this._lookUpSuccessas the function just passes the function. It doesn't pass the value of this. So, when this._lookUpSuccessis called with the wrong this, any references to thisinside of it will not find the expected properties on it (thus the error you see).

_lookupSuccess作为 done 处理程序函数传递,但是当它被调用时, 的值this不再是您想要的值,因为它将由调用 done 处理程序的任何内部设置。传递this._lookUpSuccess的功能只是传递的功能。它不传递 的值this。因此,当this._lookUpSuccess以错误的方式调用时this,对其this内部的任何引用都不会在其上找到预期的属性(因此您会看到错误)。

You can fix it like this which saves the thisvalue in a local variable and then use it when calling _lookUpSuccess():

您可以像这样修复它,将this值保存在局部变量中,然后在调用时使用它_lookUpSuccess()

var self = this;
WinJS.xhr({ url: searchUrl }).done(function(result) {self._lookUpSuccess(result)}, this._lookUpFail, this._lookUpProgress);

This is a very common work-around for reattaching the proper thisvalue in callbacks.

这是this在回调中重新附加正确值的一种非常常见的解决方法。

回答by Cerbrus

In:

在:

this._displayResult(content);

There, thisis apparently undefinedor null

那里,this显然undefinednull