我在 Controller 中得到了以下函数,我不明白为什么我不能从另一个函数调用函数 b 例如,所以我得到了以下代码:
respond: function() {
var z;
var that = this;
var y = 10;
function a() {
//do something
}
function b() {
//do something
}
function c() {
//do something
}
}
现在我尝试了这个:
respond: function() {
var z;
var that = this;
var y = 10;
function a() {
//do something
}
function b() {
//do something
}
function c() {
//do something
}
},
onButtonPress: function(){
respond.b;
},
但是这个调用不起作用,有人可以解释一下为什么吗?
最佳答案
当您声明一个函数时,它就会成为本地作用域,即对其声明的函数而言是私有(private)的。
如果您想让它在该函数外部可用,您必须通过返回它来导出它,或者将其分配给在函数外部可用的变量/对象属性。
返回:
respond: function() {
function b() {
//do something
}
return b; // Single function
}
或
respond: function() {
function a() {
//do something
}
function b() {
//do something
}
function c() {
//do something
}
// Object containing multiple functions
return {
a: a,
b: b,
c: c
};
}
分配:
respond: function() {
function b() {
//do something
}
window.b = b;
}
关于javascript - 调用 Controller 中函数内部的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002253/