javascript 闭包的优势?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6309947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript closure advantages?
提问by Jay
Whats the main purpose of Closuresin JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.
JS中闭包的主要目的是什么。它仅用于公共和私有变量吗?或者还有什么我错过的。我试图了解闭包,并且真的想知道使用它的主要优点是什么。
采纳答案by zzzzBov
I think the best phrase to sum up the purpose of closures would be:
我认为总结闭包目的的最佳短语是:
Data Encapsulation
数据封装
With a function closure you can store data in a separate scope, and share it only where necessary.
使用函数闭包,您可以将数据存储在单独的作用域中,并仅在必要时共享它。
If you wanted to emulate private static variables
, you could define a class inside a function, and define the private static vars
within the closure:
如果你想模拟private static variables
,你可以在函数中定义一个类,并private static vars
在闭包中定义:
(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}());
回答by hvgotcodes
Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible.
闭包与 javascript 的作用域有关。换句话说,由于 javascript 设计者所做的范围选择(即词法范围),闭包是可能的。
The advantage of closures in javascript is that it allows you to bind a variable to an execution context.
javascript 中闭包的优点是它允许您将变量绑定到执行上下文。
var closedIn = {};
var f = function(){
closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}
in that example, you have a normal object literal called closedIn
. It is accessed in a function. Because of that, javascript knows it has to bring closedIn
everywhere it brings the function f
, so it is available to f
.
在该示例中,您有一个名为closedIn
. 它在函数中访问。正因为如此,javascript 知道它必须将closedIn
函数带到任何它带来的地方f
,因此它可用于f
.
The this
keyword is tricky. this
is always a reference to the execution scope. You can capture the this
of one context to use in another context as follows:
该this
关键字是棘手的。 this
始终是对执行范围的引用。您可以捕获this
一个上下文的 以在另一个上下文中使用,如下所示:
var that = this;
var f = function(){
that.somethingOnThat();
// `this` means the scope f, `that` means whatever 'this' was when defined outside of the function
}
This trick can be very useful somethings, if you are coding object oriented javascript and want a callback to have access to some external scope.
如果您正在编写面向对象的 javascript 并希望回调能够访问某些外部作用域,则此技巧可能非常有用。
To quote from a Javascript book:
引用 Javascript 书籍:
"Functions in JavaScript are lexically rather than dynamically scoped. This means that they run in the scope in which they are defined, not the scopee from which they are executed. When a function is defined, the current scope chain is saved and becomes part of the internal state of the function."
“JavaScript 中的函数是词法作用域而不是动态作用域。这意味着它们在定义它们的作用域中运行,而不是在执行它们的作用域内。当一个函数被定义时,当前作用域链被保存并成为其一部分函数的内部状态。”
So the clear advantage is that you can bring any object (functions, objects, etc) along with the scope chain as far as is necessary. This is can also be considered a risk, because your apps can easily consume lots of memory if you are not careful.
因此,明显的优势是您可以根据需要将任何对象(函数、对象等)与作用域链一起带入。这也可以被视为一种风险,因为如果您不小心,您的应用程序很容易消耗大量内存。
回答by rob
Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.
由于大多数需要回调函数(例如,“onclick”函数)的 API 不提供其他机制来向这些回调函数发送参数(或显式设置“this”指针),因此在 javascript 中必须使用闭包。相反,您需要使用闭包来允许回调访问“父”函数中的变量。
I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.
我个人希望它们不是必需的,因为它们可能难以理解,使代码难以阅读(并不总是清楚范围内究竟是什么),并且会产生奇怪的错误。相反,我希望有一个允许您发送参数等的回调标准。但我接受我在这种观点中属于少数。
回答by AliN11
As we know, the variables which are defined in functions, have local scope. We can't access them from outside of the function.
众所周知,在函数中定义的变量具有局部作用域。我们无法从函数外部访问它们。
Problem 1:
问题1:
local variables are created when the function is called and they will be destroyed when the function task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.
局部变量在函数调用时创建,在函数任务完成时销毁。这意味着局部变量的生命周期比全局变量短。我们可以使用全局变量来解决这个问题。
Global variables are available when the program starts and when it ends. They are also available throughout the program.
全局变量在程序开始和结束时都可用。它们也可以在整个程序中使用。
Problem 2:
问题2:
Since global variables are accessible throughout the program, they are prone to change from everywhere.
由于全局变量可以在整个程序中访问,因此它们很容易从任何地方更改。
What do we want?
我们想要什么?
We want to have data persistence + data encapsulation.
我们要数据持久化+数据封装。
We can achieve them by using Closures
. By using a closure we can have private variables that are available even after a function task is finished.
我们可以通过使用Closures
. 通过使用闭包,即使在函数任务完成后,我们也可以获得可用的私有变量。