I've started learning JS and I'm trying to avoid using 'new' and 'this' and found my preferred method of using a factory function pattern. The downside is that instantiating new objects increases the overhead as each method is duplicated for each instance.
I then extracted each method into another object so I can use differential prototypical inheritance, i.e. each method only exists once and the calling function references this new object; this way I have both data persistence and prototypical inheritance extensibility.
Are there any pitfalls in this pattern?
var square = function(name) {
var data = { 'x1': 0, 'x2': 10, 'y1': 0, 'y2':10 };
return {
draw : function(){ square.methods.draw(data); }
};
};
square.methods = {
draw : function(data) { doStuff }
};
//usage
var newSquare = square('xyz');
newSquare.draw();
Edit:
Thanks for all the prompt replies, I sincerely appreciate all the help. I've accepted Bergi's answer as it mirrors what I was trying to do; guess I have to suck it up and use 'this' ;)
Edit 2:
I was trying to avoid constructors after reading this (scroll down to 'Closures for events and callbacks' section); each object I'll be creating will be using callbacks and his factory function solution ticked my boxes of simplicity.