Since you have jQuery available, you can use jQuery.extend()
and avoid having to retype instance1
. jQuery.extend()
copies properties from one object to another.
jQuery.extend(instance1, {
method2: method2
value4: 4
});
This will copy all the properties of the second argument to the object in the first argument. See the jQuery doc for more info.
If you wanted to specify this as part of the constructor, you could do so like this and not have any additional lines of code to type:
function myObject(value1, value2, value3, extraProperties){
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
this.method1 = method1;
if (extraProperties) {
jQuery.extend(this, extraProperties);
}
}
In that case, you would just code this:
var instance1 = new myObject(1, 2, 3, {method2: method2, value4: 4});
Of course, the more Object Oriented way to do this would be to create prototypes for each type of object you want (some could inherit from others) and then just instantiate the right type of object rather than add instance-specific methods and properties.
Or, create a single prototype that has all the methods/capabilities you might need on it for all the uses of the object rather than adding instance specific methods. In javascript, there is no penalty for having methods on an object that you don't use sometimes if they are on the prototype. Things on the prototype are free per instance (no storage consumption per instance, no initialization cost per instance, etc...).