I have a couple of javascript objects that each have a setup method. The code is identical for all of them so I created a function called setupMain. Then for each instance of the object I’m trying to set it’s setup value to setupMain. something like below… but when I look at the setup value after an instance is created, it’s coming back undefined instead of pointing to the setupMain function. Any idea why? Thanks.
var customObject = function(){
this.title = "";
}
var setupMain = function(obj){
obj.title = "initial setup value";
}
var co = new customObject();
co.setup = setupMain(co);
You might be looking for something like this:
Also, if you don’t want to have to keep setting the
setupfunction each time to create an instance, you can move it to the prototype:Finally, if you didn’t want to have to call
setup();each time, you can callsetupwithin the constructor: