Whenever I create a Javascript "class" I do something like this:
// Definition
function MyObject() {
this.id = 0;
this.legs = 2;
}
MyObject.prototype = {
walk: function() {
// Do stepping
},
stop: function() {
// Stop stepping
}
};
// Instanciation
var TestMyObject = new MyObject();
TestMyObject.id = 1;
TestMyObject.legs = 3;
However, as I was trying to find a way to do fixed time step timers, I found another way to construct objects by passing in a key value pair object. That got me thinking that it could be convenient to construct MY objects in a similar fashion. So is there a problem with creating an object like this:
// Definition
function MyObject(objectSettings) {
// Essentially acts as default constructor
objectSettings = objectSettings || {};
// Without a given parameter, use default
this.id = objectSettings.id || 0;
this.legs = objectSettings.legs || 2;
// Make sure the reference is gone
objectSettings = null; // Do I even need this?
}
MyObject.prototype = {
walk: function() {
},
stop: function() {
}
};
// Instanciation
// Use all defaults
var TestMyObject01 = new MyObject();
// Set only id
var TestMyObject02 = new MyObject({
id: 1
});
// Set everything
var TestMyObject02 = new MyObject({
id: 1,
legs: 3
});
My question is, objectSettings
doesn't stick around after instantiating the new object right? Maybe I'm being paranoid. I'm still trying to wrap my head around closures and initially I had a var
inside the definition that referenced the passed objectSettings
but I figured that was a bad choice because that would be a private immutable reference to a hunk of memory that was just used to copy into an object and that memory wouldn't go away as long as the created object was around.
I realize it would probably be even easier to pass values in individually to the constructor, but I thought maybe this would be a way to overcome the limitation of not being able to overload a function based on parameter type. I would pass what I want to set specifically and if it isn't in the passed object (or if there is no passed object at all) the parameter would be set to a default value. Is there a better way to construct objects in a similar fashion?
I can't find the link to the timer object that got me on this but If I do find it, I'll link it here.