0
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?

0

2 Answers 2

2

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;
   });   
};
4
  • Well, getId will return undefined, unless id is explicitly set somewhere else. So yes, it's not referencing the same id that you declared as private in the constructor.
    – beatgammit
    Nov 25, 2012 at 6:38
  • Given your code example, id is not accessible anywhere except in the constructor. You can get around this by creating closures in the constructor (my first example), but there's no way to access id outside of the constructor.
    – beatgammit
    Nov 25, 2012 at 6:47
  • Thanks for your time tjameson, you helped a lot
    – sanchez
    Nov 25, 2012 at 6:56
  • If you don't need to support older browsers, you can use Object.defineProperty(this, "id", {value: data, writable: false}). See mdn documentation for more info.
    – beatgammit
    Nov 25, 2012 at 7:11
0

Maybe you can rewrite a bit:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.