0

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...

2 Answers 2

1

You constructor function is only called when you instantiate the object. If you want to reuse the object, you'll want to instantiate it the first time (to do initialization) and then call an instance method for the actual work"

var testobj;

function test(thing) {

    var self = this;

    if(!testobj) {
        testobj = new testObj();
    }

    testobj.someMethod(thing);
};

But unless your constructor function is really expensive, I wouldn't worry about the performance in response to a user click and skip the caching.

Sign up to request clarification or add additional context in comments.

Comments

1

It's because new thing() returns an regular object, not a function.

What you should do is just work with the object after the initialization.

var my_object;

function Thing() {
   this.thing = 'a sentence';
   console.log('calling');
}

Thing.prototype.amethod = function() {
   this.thing = 'a method of thing'
}

// new test(); // not necessary

var button = document.getElementsByTagName('button')[0];
button.onclick = function() {
    if (!my_object)
        my_object = new Thing();

    // do some work with my_object
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.