简体   繁体   中英

assigning method to another method in javascript

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:

var customObject = function(){
  this.title = "";
}
var setupMain = function(){ //"This" will point to instance, such as co
  this.title = "initial setup value";
}

var co = new customObject();
co.setup = setupMain; //Reference to function

co.setup(); //Call the setup function
window.alert(co.title);

Also, if you don't want to have to keep setting the setup function each time to create an instance, you can move it to the prototype:

customObject.prototype.setup = setupMain; //Now, every customObject has a setup function
var co = new customObject();
co.setup();
window.alert(co.title);

Finally, if you didn't want to have to call setup(); each time, you can call setup within the constructor:

var customObject = function(){
  this.setup(); //Call shared setupMain function because it's part of the prototype
}
var setupMain = function(){
  this.title = "initial setup value";
}

customObject.prototype.setup = setupMain; //This can be shared across many prototypes

var co = new customObject();
window.alert(co.title);

Your code evaluates setupMain(co) and assigns the result to c.setup... Therefore:

  • setupMain sets co.title to "initial setup value"
  • setupMain returns undefined
  • co.setup is set to undefined

You should assign the function to your variable, such as:

var setupMain = function() {
    this.title = "initial setup value";
}
...
co.setup = setupMain; // Without the ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM