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,
idis only accessible from within your constructor.You can keep
idprivate 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:Another problem is that you’re trying to access
thisfrom within an asynchronous callback. In this context (the callback passed to$.post),thisis 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
thisof you function (from your original code, assumingidis not private):