I’m struggling to learn object oriented javascript. I have an object constructor that looks like this:
//generic object
function myObject(value1, value2, value3){
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
this.method1 =method1;
}
function method1(){
alert('hello');
}
function method2(){
alert('hello again');
}
I’m creating new instances of this object like this:
instance1 = new myObject(
1, //value1
2, //value2
3 //value3
)
My problem is this: On a few instances of myObject I need custom values and methods. I would like to add them at the point of creation. But I can’t figure out how to do it without writing the instance name again, which I’m trying to avoid since it would significantly slow down the process of adding new objects.
Is there some way to replace this code..
instance1 = new myObject(
1, //value1
2, //value2
3 //value3
)
instance1.method2 =method2;
instance1.value4 =4;
..with something that doesn’t require repeating the name “instance1”?
Since you have jQuery available, you can use
jQuery.extend()and avoid having to retypeinstance1.jQuery.extend()copies properties from one object to another.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:
In that case, you would just code this:
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…).