将方法附加到javascript函数,然后将它们传递给变量
我有一个javascript函数(使用NodeJS,但在这里并不特别相关),如下所示:将方法附加到javascript函数,然后将它们传递给变量,javascript,variables,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'];
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]
,则返回:“一”
但是,如果我打电话:
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”
如果要引用方法。请在应用程序中创建,然后使用它,可以使用第一个表达式(不带()
):
为什么会这样method.create()。将函数指定为函数对象上的属性也是相当不寻常的,尽管在某些情况下它肯定是有用的(例如,KnockoutJS使用observables来指定函数,当然所有普通JavaScript函数上都有方法,比如call
,apply
,…)。
var app = method.create;
app.function1(); // Works