我有一个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'];
}
但这根本不起作用。我能做些什么来将这些方法传递给一个新的变量?
答案 0 :(得分:2)
表达式method.create
和method.create()
之间存在很大差异。第一个结果是对函数对象的引用;第二个调用函数并返回其返回值。由于您的create
函数没有返回任何内容,因此调用它的结果是值“未定义。”
如果您希望在method.create
中引用app
然后使用它,则使用第一个表达式(不 ()
):
var app = method.create;
app.function1(); // Works