简体   繁体   中英

Can't access class member

function Example(){
     var id;
};

Example.prototype.getId = function(){
     // return this.id; 
};

Example.prototype.init = function(){
   $.post( 'generateId.php', {}, function(data){
       // this.id = data; 
   });   
};

How can I access id within these functions?

It seems that you think "private" variables exist in Javascript. Private variables are only emulated in Javascript through closures, but do not exist as in other languages. In your code, id is only accessible from within your constructor.

You can keep id private though, and still be able to access it from within your functions, but you'll have to declare those functions in your constructor as closures to have access to it:

function Example()
{
    //private
    var id;

    this.getId = function ()
    {
        return id;
    }

    this.init = function()
    {
       $.post( 'generateId.php', {}, function(data)
       {
           id = data;
       });   
    };
};

Another problem is that you're trying to access this from within an asynchronous callback. In this context (the callback passed to $.post ), this is whatever the context of the calling function was, which is probably undefined or the XmlHTTPRequest object.

If you want to access it, you'll have to cache the this of you function (from your original code, assuming id is not private):

Example.prototype.init = function()
{
   var self = this;
   $.post( 'generateId.php', {}, function(data)
   {
       self.id = data;
   });   
};

Maybe you can rewrite a bit:

var Example = Example || {};
Example.id = "";

Example.init = function(){
$.post( 'generateId.php', {}, function(data)
{
   Example.id = data; // <-------- error
});  
}

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