将方法附加到javascript函数,然后将它们传递给变量

时间:2014-04-26 07:57:05

标签: javascript variables

我有一个javascript函数(使用NodeJS但在这里不是特别相关),如下所示:

var method = {};
method.create = function(){
  console.log('Method was created')
}

method.create.function1 = function(){
  console.log("This is method 2")
}

method.create.series = ['one', 'two', 'three'];

如果我拨打method.create.function1(),它会正确运行该功能和控制台日志:This is method 2

如果我致电method.create.series[0],我将退回:"one"

但是,如果我打电话:

 var app = method.create();
 app.function1() // returns undefined

我试过了:

var method = {};
method.create = function(){
    console.log('Method was created')

    this.function1 = function(){
      console.log("This is method 2")
    }

    this.series = ['one', 'two', 'three'];
}

但这根本不起作用。我能做些什么来将这些方法传递给一个新的变量?

1 个答案:

答案 0 :(得分:2)

表达式method.createmethod.create()之间存在很大差异。第一个结果是对函数对象的引用;第二个调用函数并返回其返回值。由于您的create函数没有返回任何内容,因此调用它的结果是值“未定义。”

如果您希望在method.create中引用app然后使用它,则使用第一个表达式( ()):

var app = method.create;
app.function1(); // Works