I need to creat an object everytime someone clicks on a button:
var button = document.getElementsByTagName('button')[0];
button.onclick = function() {
new testobj(args);
}
function testObj(args) {
}
testObj.protoype.method = function() {
//...
}
but it seems wasteful to keep creating a new object each time the button is clicked (mainly because that object just receives a value and does something with it and then returns). I wondered if there was a way to create the object on the first time the button is clicked and then on subsequent clicks just run that object again somehow...
So I tried this:
var testobj;
function test(thing) {
var self = this;
if(!testobj) {
testobj = new thing(thing);
} else {
testobj(thing);
}
};
This just assigns the thing object to the testobj var first time test() is run...after that I just try to call testobj again...but I get a object is not a function error error. Full test here http://jsfiddle.net/pstbj/1/
I understand why I get the error, because testobj is an object and not a function. Is there any way to make this work as I want...so that I only create the object once.
or perhaps creating a new object isn't so bad...I'm imagining that it's not good practice to keep creating object needlessly? I'm thinking I need to cache the object...