Keeps saying result property is not defined. Why?

前端 未结 3 1101
一生所求
一生所求 2021-01-23 08:16

Here is my object and I have defined all the properties and functions but it still gives me this error result is not defined.

Here is my code



        
3条回答
  •  悲哀的现实
    2021-01-23 09:01

    The "undecorated" expression result would refer to a global variable named result, which you do not have.

    It is not correct to assume that just because a reference to result is textually inside of an object that the reference refers to a property of that object. That may be the case in other languages, but not in JavaScript.

    The solution to your problem is in one of the comments to the question. Using this. as a prefix works in these cases. Try this code:

    var x = 1;
    
    var p = {
       x: 2,
       f: function () {alert(x); alert(this.x);}
    }
    
    p.f();
    

    Here you will see 1 alerted and then 2.

    Answer to updated question

    What you have here is a classic problem. You write

    var xml = Xml.init(from, to, fromurl);
    console.log(xml.getResult()); //<---- calling getResult();
    

    The first line eventually fires of an Ajax request. Once that request is fired off, you immediately go to your second line, where you call xml.getResult(). Chances are nearly 100% that the call to getResult will happen before your Ajax call is able to fill in the value of result.

    One approach is to pass the thing you want to do with the result to the init method. In this case it looks like you want to log the result, so try

    var xml = Xml.init(from, to, fromurl, function () {console.log(xml.getResult()});
    

    Here we have a new fourth parameter to Xml.init so we have to handle that by updating the Xml object, like so (not tested):

    .
    .
    .
    init: function (fromaddress, toaddress, link, callback) {
        from    = fromaddress;
        to      = toaddress;
        url     = link;
    
        this.requestXml(callback);
        return this;
    },
    
    requestXml: function (callback) {
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            success: callback
        });
    },
    
    .
    .
    .
    

    In other words, when you are going to make asynchronous calls, consume the results right away. Don't save them away for later, because you never know when they are going to be "ready".

提交回复
热议问题