Google JavaScript Style Guide上看到一段关于闭包的写法,先贴内容:
One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a result, attaching a closure to a DOM element can create a circular reference and thus, a memory leak. For example, in the following code:
function foo(element, a, b) {
element.onclick = function() { /* uses a and b */ };
}
the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection. In these situations, the code can be structured as follows:
function foo(element, a, b) {
element.onclick = bar(a, b);
}
function bar(a, b) {
return function() { /* uses a and b */ }
}
Google JavaScript Style Guide
精选 翻译yangbin1103 博主文章分类:js/css/html
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
[Guide]Google C++ Style Guide
0.0 扉页 项目主页 Google Style Guide Google 开源项目风格
C/C++ Style 命名空间 头文件 #include -
Google coding Style Guide : Google 编码风格/代码风格 手册/指南
Google 编码风格/代码风格 手册/指南google styleguide e
Google Google编码风格手册 Google 代码风格指南 styleguide 编码风格