[英]Is it possible to use inner functions in JavaScript?
How can I get access to my y()
function? 如何访问我的
y()
函数?
function x() {
function y() {
return 1;
}
}
Is it possible at all? 有可能吗?
It is scoped to x
, kind of like: 它的范围是
x
,有点像:
function x() {
var y;
}
So, yes, from within x
, and no otherwise. 所以,是的,从
x
内,否则没有。
If you wanted it to be, you could create it as a property on x
: 如果你想要它,你可以在
x
上创建它作为属性:
var x = (function () {
function x() {
…
}
function y() {
…
}
x.y = y;
return x;
})();
You mean access it from outside the function x
? 你的意思是从函数
x
外部访问它?
That's not possible, the function y
doesn't exist when x
is not running. 这是不可能的,当
x
没有运行时,函数y
不存在。 It's declared locally inside x
so it's only accessible inside x
. 它在
x
内部声明,因此只能在x
内部访问。
To make it accessible outside x
you need to expose a reference to it outside the function. 要使它在
x
外部可访问,您需要在函数外部公开对它的引用。 If you expose a reference to it, it survives after the function ends. 如果公开对它的引用,它将在函数结束后存活。 For example:
例如:
function x() {
function y() {
return 1;
}
return y;
}
// get the reference to y
var f = x();
// call y
f();
You can get access to your y function inside of the scope of the x function Only. 你可以得到只有X功能的范围内访问您的y功能。 But you can get access to the y function if you return it from your x function or assign it to a global variable or to the variable that is in scope outside of your x function.
但是,如果从x函数返回y函数或将其分配给全局变量或x函数之外的变量,则可以访问y函数。 This is also know is closure , your y function will keep the reference in memory to the scope it was created in if you pass it around.
这也知道是闭包 ,你的y函数会将内存中的引用保留在它传递给它的范围内。
function x() {
var anotherNum= 2;
function y() {
return 1 + anotherNum;
}
return y;
}
Now you can get the y function along with the scope it was created in. Notice that it will use anotherNum in the computation as it was created in the x function. 现在你可以得到y函数以及它所创建的作用域。请注意,它将在x函数中创建的计算中使用anotherNum。
var yFunc = x();
console.log(yFunc()) // will print 3
One way is to return it out of the scope 一种方法是将其退出范围
function x() {
function y() {
return 1;
}
return {
y:y
};
}
Whenever you call x(), it returns an object with the function y as a member 每当调用x()时,它都会返回一个函数为y的对象作为成员
var a = x();
a.y(); //this returns 1
This is similar to the revealing module pattern described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures 这类似于此处描述的揭示模块模式: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redloclale = en-US&redirectslug = JavaScript%2FGuide%2FClosures
Also good to read up on closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures 阅读闭包也很好: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures? redloclale = en-US & redirectslug = JavaScript%2FGuide% 2FClosures
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.