Template for LampPost objects. Create instances with LampPostTemplate.create().
// Helper function to create copies of a template object and then copy
// arbitrary properties based on an input dictionary.
function createInstanceFromTemplate(templateObject, instanceVariableDictionary) {
var result = Object.create(templateObject);
for (var property in instanceVariableDictionary) {
if (typeof instanceVariableDictionary[property]['slice'] === 'function') {
// Copy an array
result[property] = instanceVariableDictionary[property].slice();
} else if (typeof instanceVariableDictionary[property] === 'object') {
// Copy an object
result[property] = Object.create(instanceVariableDictionary[property]);
} else {
// Copy numbers, strings, ...
result[property] = instanceVariableDictionary[property];
}
}
return result;
};
// Template for LampPost objects. Create instances with LampPostTemplate.create().
LampPostTemplate = {
create:function(instanceVariableDictionary) {
var result = createInstanceFromTemplatecreateInstance(this, instanceVariableDictionary);
//... any initialization code needed for LampPost instances.
result.flickerAnimationTimeOffset = Math.random();
return result;
},
draw:function() { /* ... */ },
center:{x:.5, y:.5},
position:{x:0, y:0},
name:"Unnamed",
flickerAnimation: [1,1,1,1,1,0,1,1,0,1,1,1,0],
flickerAnimationTimeOffset: 0
};
// ...
// Create instances:
Create instances:
Lamp1 = LampPostTemplate.create({ position:{x:1, y:2} });
Lamp2 = LampPostTemplate.create({
position:{x:11, y:22},
flickerAnimation:[1,0,0,0,0,1,0,0],
name:"Hill top2"});
Here is the helper function to create copies of a template object and then copy arbitrary properties based on an input dictionary.
function createInstance(templateObject, instanceVariableDictionary) {
var result = Object.create(templateObject);
for (var property in instanceVariableDictionary) {
if (typeof instanceVariableDictionary[property]['slice'] === 'function') {
// Copy an array
result[property] = instanceVariableDictionary[property].slice();
} else if (typeof instanceVariableDictionary[property] === 'object') {
// Copy an object
result[property] = Object.create(instanceVariableDictionary[property]);
} else {
// Copy numbers, strings, ...
result[property] = instanceVariableDictionary[property];
}
}
return result;
};