将方法分配给javascript中的另一个方法

时间:2012-02-06 17:01:10

标签: javascript

我有几个javascript对象,每个对象都有一个设置方法。所有这些代码都相同,所以我创建了一个名为setupMain的函数。然后对于对象的每个实例,我试图将它的设置值设置为setupMain。类似于下面的内容......但是当我在创建实例后查看设置值时,它将返回undefined而不是指向setupMain函数。知道为什么吗?感谢。

var customObject = function(){
  this.title = "";
}
var setupMain = function(obj){
  obj.title = "initial setup value";
}

var co = new customObject();
co.setup = setupMain(co);

2 个答案:

答案 0 :(得分:1)

你可能正在寻找这样的东西:

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);

另外,如果您不想每次都要设置setup函数来创建实例,可以将其移动到原型:

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

最后,如果您不想每次都致电setup();,可以在构造函数中调用setup

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);

答案 1 :(得分:0)

您的代码评估setupMain(co)并将结果分配给c.setup ...因此:

  • setupMain将co.title设置为“初始设置值”
  • setupMain返回undefined
  • co.setup设置为undefined

您应该将函数分配给变量,例如:

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