Javascript - 命名空间与闭包之间的区别? [英] Javascript - difference between namespace vs. closure?

查看:149
本文介绍了Javascript - 命名空间与闭包之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,命名空间和闭包有什么区别?



具体来说,本文讨论命名空间和关闭,并有类似

的句子


现在,我们仍然需要声明
变量,这些变量自然不适合命名空间对象
结构。但是我们不希望这些变量具有全局范围。这是
自调用函数的地方。


它看起来很像一个闭包,作为对象名称空间。它看起来像我的名字空间是一个关闭,但也许不是...?帮助?

解决方案

命名空间本质上是一个没有有趣属性的 Object 你推送的东西,所以你没有一堆变量,类似和/或冲突的名称围绕你的范围。因此,例如,像

  MyNS = {} 
MyNS.x = 2
MyNS。 func = function(){return 7; }

一个闭包是当一个函数保留未定义的变量的值时,即使这些变量已经超出范围。采取以下操作:

  function makeCounter(){
var x = 0;
return function(){return x ++; }
}



如果我让 c = makeCounter / code>然后重复调用 c(),我会得到 0,1,2,3, code>。这是因为 makeCounter x 中定义了closed的内部匿名函数的作用域,

值得注意的是,如果我然后做 d = makeCounter() d()将从0开始计数。这是因为 c d 获取 x 的不同实例。


In Javascript, what's the difference between a namespace and a closure? They seem very similar to me.

EDIT

Specifically, this article discusses namespaces and closures, and has sentences like

Now, we’re still going to have situations where we’ll want to declare variables that don’t naturally fit into a namespaced object structure. But we don’t want those variables to have a global scope. This is where self-invoking functions come in.

It goes on to give what looks a lot like a closure, as an "object namespace". It looks to me like the namespace IS a closure...but maybe it's not...? Help?

解决方案

A namespace is essentially an Object with no interesting properties that you shove stuff into so you don't have a bunch of variables with similar and/or conflicting names running around your scope. So, for example, something like

MyNS = {}
MyNS.x = 2
MyNS.func = function() { return 7; }

A closure is when a function 'retains' the values of variables that are not defined in it, even though those variables have gone out of scope. Take the following:

function makeCounter() { 
   var x = 0;
   return function() { return x++; }
}

If I let c = makeCounter() and then repeatedly call c(), I'll get 0, 1, 2, 3, .... This is because the scope of the inner anonymous function that makeCounter defines 'closes' over x, so it has a reference to it even though x is out of scope.

Notably, if I then do d = makeCounter(), d() will start counting from 0. This is because c and d get different instances of x.

这篇关于Javascript - 命名空间与闭包之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆