我有一个 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()
它会正确运行该函数并控制台日志:这是方法 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'];
}
但这根本不起作用。我能做些什么才能将这些方法传递给新变量?
最佳答案
表达式 method.create
和 method.create()
之间存在很大差异。第一个结果是对函数对象的引用;第二个调用该函数并产生其返回值。由于您的 create
函数不返回任何内容,因此调用它的结果是值“undefined”。
如果您想在 app
中引用 method.create
并使用它,请使用第一个表达式(不带 ()
):
var app = method.create;
app.function1(); // Works
关于javascript - 将方法附加到 javascript 函数,然后将它们传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308272/