繁体   English   中英

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

[英]assigning method to another method in javascript

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

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

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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