简体   繁体   中英

Javascript OOP class - assigning property to function

Perhaps this has already been addressed, but couldn't find a suitable answer here. Apologies if it's the case. Here's the issue :

function Aclass(){

    this.value1 = "a first value"
    this.value2 = pulldata()

    function pulldata(){
        $.getJSON("data.json",function(data){
            return data
        })
    }
}

var obj = new Aclass()
console.log(obj.value1)
console.log(obj.value2)

Result : "a first value" then "undefined" The data var isn't available out of the pulldata's scope, and I'm not sure what's the best way around this.

Your pullData() function doesn't actually return anything explicitly, so its return is undefined - which means what you are seeing when you log obj.value2 is correct (though undesired).

Inside pullData() you are calling $.getJSON() and passing it an anonymous function as a callback, and it is that anonymous function that returns data but the return doesn't go anywhere because the ajax call is asynchronous and the callback doesn't occur until later.

You could try this:

function Aclass(classInitialisedCallback){
    var self = this;

    this.value1 = "a first value";
    this.value2 = "not available yet";

    $.getJSON("data.json",function(data){
        self.value2 = data;
        if (typeof classInitialisedCallback === "function")
           classInitialisedCallback(self);
    });
}

var obj = new Aclass(function(newInstance) {
   // can use obj or newInstance to refer to the object
   console.log(obj.value1);
   console.log(newInstance.value2);
});

That is, set up your Aclass() constructor to take a parameter that is a callback function to be executed when the class is ready, ie, after the result from $.getJSON() is available.

$.getJSON makes an asynchronous ajax call to your "data.json" URL. The second argument you've given it is the callback, which is called when the ajax call is finished. Your pulldata function, however, just runs through without waiting for the answer and, thus, returns undefined.

It's not possible to do exactly what you're trying to do with asynchronous calls (and you should never use synchronous calls).

You'll have to rewrite your code to do your stuff in the callback instead. The callback is your "function(data){}" argument.

If the function you called wasn't asynchronous however, this is how the JS scope works and should've solved your problem:

function Aclass() {
    var that = this;
    this.value2 = 'not set';

    var pullData = function() {
        someCallToSomethingWithACallback(function() {
            that.value2 = 'set';
        }
    }
}

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