Forum Moderators: open
How do I get private methods in an object to work?
function ajax()
{
this.xhr = false; // AJAX XMLHttpRequest Variable function NewXMLHttpRequest()
{
if (window.XMLHttpRequest) // native XMLHttpRequest object
{
try { this.xhr = new XMLHttpRequest(); }
catch(e) { this.xhr = false; }
}
else if (window.ActiveXObject) // IE/Windows ActiveX version
{
try { this.xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e)
{
try { this.xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e) { this.xhr = false; }
}
}
}
NewXMLHttpRequest();
}
var a = new ajax();
alert(a.xhr);
I dont want to change function NewXMLHttpRequest() to this.NewXMLHttpRequest = function () { ... }
Thanks
function ajax()
{
var that = this;
this.xhr = false; // AJAX XMLHttpRequest Variable
var NewXMLHttpRequest = function()
{
if (window.XMLHttpRequest) { // native XMLHttpRequest object
try {
that.xhr = new XMLHttpRequest();
}
catch(e) {
that.xhr = false;
}
}
else if (window.ActiveXObject) { // IE/Windows ActiveX version
try {
that.xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
that.xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
that.xhr = false;
}
}
}
};
NewXMLHttpRequest();
}
var a = new ajax();
alert(a.xhr);
Anyway, I learnt that nested methods are replicated instead of being shared across instances. That would be a waste having a private method for each instance.
function ajax()
{
this.xhr = false; // AJAX XMLHttpRequest Variable
this.NewXMLHttpRequest();
}ajax.prototype.NewXMLHttpRequest = function()
{
}
Anyway, I learnt that nested methods are replicated instead of being shared across instances. That would be a waste having a private method for each instance.
A waste? It depends on what you're doing. If you want to ensure that the method is private and can only be called from within the object instance, then it's going to be a requirement. But if you want a public method that can be called from outside of the object instance, then adding it to the prototype would be the better alternative.
Note, this issue of "wasting" memory by replicating methods for each instance is probably not as big of an issue as you might think. Are you going to be passing your object to other functions after you create it? Are you going to be creating many instances of your object? Even if you do, the impact for today's computer is insignificant (in my experience).
Also, newer methods for creating objects are gaining in popularity. Lookup JSON (JavaScript Object Notation).
Hope that helps.