[英]How to access a function inside another function
How do I call the inner function from outside in the following code ? 如何在以下代码中从外部调用内部函数?
(function (){
var funOne = {
funTwo : function (){
var funFour = function(){
console.log('inner function working');
}
},
funThree : function () {
console.log('working');
}
}
funOne.funTwo(); // works
funOne.funThree(); // works again
funOne.funTwo.funFour(); // throwing exception
})();
You have a scoping issue with funFour compounded by trying to define funTwo act as a function ( funOne.funTwo()
) and an object ( funOne.funTwo.funFour()
). 通过尝试将funTwo定义为一个函数(
funOne.funTwo()
)和一个对象( funOne.funTwo.funFour()
),使funFour遇到了一个范围界定问题。
Here are 2 options to get access to funFour: 这是2个可以访问funFour的选项:
funTwo()
in your output. funTwo()
。 How to change funTwo: 如何改变乐趣二:
funTwo : function (){
var funFour = function(){
console.log('inner function working');
};
funOne.funFour = funFour; // Option 1
return { 'funFour': funFour }; // Option 2
},
How to call each option: 如何调用每个选项:
funOne.funFour(); // Option 1
funOne.funTwo().funFour(); // Option 2
There is no way to access Local variable (var funFour) of function funTwo from outside. 无法从外部访问功能funTwo的 局部变量 (var funFour)。 If you want to use funFour at outside of function funTwo, you need to declare funFour as Global variable .
如果要在funTwo函数外部使用funFour ,则需要将funFour声明为Global variable 。
Edited code is here. 编辑的代码在这里。
(function (){
var funFour;
var funOne = {
funTwo : function (){
funFour = function(){
console.log('inner function working');
}
},
funThree : function () {
console.log('working');
}
}
funOne.funTwo(); // works
funOne.funThree(); // works again
funFour(); // Call function funFour here
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.