I\'m trying to work out the best way to modify an object without writing out a similar object three times. So I have these three objects:
var object1 = {
sta
I assume you want to create multiple sets of objects with the same start/end pair, but different types.
One approach would be write a function, to which you'd pass a start/end pair, and which returns a function to create an object with a particular type:
function make_creator(start, end) {
return function(type) {
return { start, end, type };
};
}
Now you can create your objects as
var creator = make_creator(start, end);
var object1 = creator(1);
var object2 = creator(2);
var object3 = creator(3);
In this case, you can think of the make_creator
function as "storing" the values of start
and end
for use within the returned closure. It's conceptually related to "storing" them within the "template" proposed in another answer.
Let's consider using prototypes. It's not usually a good idea idea to place values in prototypes. You are likely to shoot yourself in the foot when you try to set the property and end up creating a sort of shadow value on the instance. Any performance (memory) differences will be miniscule unless you have a million objects, and will outweighed by the cost of finding the property on the prototype chain. More importantly, if you want multiple sets of objects with the same start/end pair, you'd have to create separate prototypes for each.
I'm not quite sure why or when we all started worrying quite so much about performance. The bottom line is that the difference in performance (either memory or speed) between any alternatives is going to be miniscule. (The exception is if you are creating millions or tens of millions of these objects.) The guiding principle should be to find an approach which is easy to write, easy to read, and easy to maintain. If you are creating tens of millions of objects, and you determine by profiling your program that this particular area is the bottleneck, then that would be the time to go back and optimize it.