如何使javascript函数在内部和外部可见
我显然不理解这里Javascript的语义(就像我对其他更传统的语言所做的那样)。任何指导都将不胜感激 简而言之,如何使javascript函数在内部和外部可见,javascript,Javascript,我显然不理解这里Javascript的语义(就像我对其他更传统的语言所做的那样)。任何指导都将不胜感激 简而言之,func2()必须可以在内部调用到main(),也可以在外部调用(例如,main().func2()): 第一个样本: var main = function () { var func1 = function () { console.log('in func1()'); // *** does not work
func2()
必须可以在内部调用到main()
,也可以在外部调用(例如,main().func2()
):
第一个样本:
var main = function () {
var func1 = function () {
console.log('in func1()');
// *** does not work
func2();
};
return {
// externally visible (eg, from other() below)
func2: function () {
console.log('in func2()');
},
init: function () {
func1();
}
};
};
var other = function () {
main().init();
main().func2(); // *** works
}
结果:
other();
VM1070:5 in func1()
VM1070:7 Uncaught ReferenceError: func2 is not defined
at func1 (<anonymous>:7:9)
at Object.init (<anonymous>:16:13)
at other (<anonymous>:22:12)
at <anonymous>:1:1
other()
VM1097:5 in func1()
VM1097:11 in func2()
VM1097:11 in func2()
VM1097:24 Uncaught TypeError: main(...).func2 is not a function
at other (<anonymous>:24:12)
at <anonymous>:1:1
other @ VM1097:24
(anonymous) @ VM1117:1
结果:
other();
VM1070:5 in func1()
VM1070:7 Uncaught ReferenceError: func2 is not defined
at func1 (<anonymous>:7:9)
at Object.init (<anonymous>:16:13)
at other (<anonymous>:22:12)
at <anonymous>:1:1
other()
VM1097:5 in func1()
VM1097:11 in func2()
VM1097:11 in func2()
VM1097:24 Uncaught TypeError: main(...).func2 is not a function
at other (<anonymous>:24:12)
at <anonymous>:1:1
other @ VM1097:24
(anonymous) @ VM1117:1
other()
功能1()中的VM1097:5
功能2中的VM1097:11()
功能2中的VM1097:11()
VM1097:24未捕获类型错误:main(…)。func2不是函数
其他时间(:24:12)
时间:1:1
其他@VM1097:24
(匿名)@VM1117:1
如何在main()
中定义func2()
,以便可以从任何地方调用它
谢谢您必须为返回的对象创建
func1
和func2
属性。实际上,它们只是main()
函数中的本地符号
var main = function () {
var func1 = function () {
console.log('in func1()');
// *** works
func2();
};
var func2 = function () {
console.log('in func2()');
};
return {
init: function () {
func1();
func2();
},
func1: func1,
func2: func2
};
};
看起来您可能会发现ES6类对于该逻辑更有趣:在另一个函数中声明变量或函数不会使其成为对象的一部分。