I have a Javascript class that contains a few functions and member objects:
function MyUtils()
{
// Member Variables (Constructor)
var x = GetComplexData();
var y = DoSomeInitialization();
// Objects
this.ParamHash = function()
{
// Member variables
this.length = 0;
this.items = new Array();
// Constructor
for (var i = 0; i < arguments.length; i += 2)
{
// Fill the items array.
this.items[arguments[i]] = arguments[i+1];
this.length++;
}
}
// Functions
this.DoSomething = function()
{
// Do something.
// Uses the items in the ParamHash object.
for (var i in this.ParamHash.items)
{
// Really do something!
}
// Clear the ParamHash object -- How??
}
}
This is invoked in the following manner:
// First call - works fine.
var utils = new MyUtils();
utils.ParamHash = new utils.ParamHash("a", 1, "b", 2);
utils.DoSomething();
// Don't want to re-initialize.
// utils = new MyUtils();
// Consequent call - crashes ["Object doesn't support this action."].
utils.ParamHash = new utils.ParamHash("c", 3);
utils.DoSomething();
The problem arises from the restriction that I want to reuse the same utils
object throughout the code without having to re-initialize it. Also, I want the ParamHash object to be recreated from scratch everytime I call it. However, consequent calls to the ParamHash constructor throw an error "Object doesn't support this action." At this stage, I can see that the utils.ParamHash object still contains the old values ("a", "b").
I have tried various ways to clear the ParamHash object such as setting it's items and length to null, popping items from the array. Nothing seemed to work until I used the following way (in the DoSomething()
function):
this.ParamHash.items = new Array();
this.ParamHash.length = 0;
This seems wrong because what if I had a lot of member variables... would I have to reset each of them individually?
So, the question is: What is the best way to reset the ParamHash
object to the initial state? I'm sure hoping that there is a cleaner/more direct way. Something like :
// Doesn't work! :-(
this.ParamHash = new function() {};
EDIT: I'm looking for a cross-browser solution - One that works atleast in IE6+ and FF 2+.
Solution: Thanks to Cristoph, I was able to do it by creating a separate variable/property within MyUtils
which only holds the instance of the ParamHash
function.
function MyUtils()
{
// Same ol' stuff.
var myParamHash;
}
// First call - works fine.
var utils = new MyUtils();
utils.myParamHash = new utils.ParamHash("a", 1, "b", 2);
utils.DoSomething();
// Consequent call - works fine now.
utils.myParamHash = new utils.ParamHash("c", 3);
utils.DoSomething();