是否可以访问函数的闭包? [英] Is it possible to gain access to the closure of a function?

查看:134
本文介绍了是否可以访问函数的闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的函数通过保留(隐藏)链接到其封闭范围来形成闭包。

A function in javascript forms a closure by keeping a (hidden) link to its enclosing scope.

当我们有函数(作为变量值)时,是否可以以编程方式访问它?

Is it possible to access it programmatically when we have the function (as a variable value) ?

真正的目标是理论上的,但演示可以列出闭包的属性。

The real goal is theoretical but a demonstration could be to list the properties of the closure.

var x = (function(){
   var y = 5;
   return function() {
       alert(y);
   };
})();

//access y here with x somehow


推荐答案

这是(一个)闭包的目的 - 保持信息私有。由于函数已经被执行,其范围变量不再可以从外部使用(并且从未被使用过) - 只有在其范围内(仍然)执行的函数才能访问。

That's (one of) the purpose(s) of a closure - to keep information private. Since the function already has been executed its scope variables are no longer available from outside (and have never been) - only the functions executed in it's scope (still) have access.

但是,您可以通过getters / setters授予访问权限。

However you could give access via getters/setters.

您可能需要查看 Stuart Langridge的谈话关于闭包。非常值得推荐的还有Douglas Crockfords的解释。你可以使用闭包做很多奇特的事情;)

You might want to take a look into Stuart Langridge's talk about closures. Very recommendable are also Douglas Crockfords Explanations. You can do lots of fancy stuff with closures;)

编辑:
你有几个选项来检查闭包:在webdeveloper控制台中观察对象,或者我经常这样做)返回一个调试函数,它将所有的私有变量转储到控制台。

You have several options to examine the closure: Watch the object in the webdeveloper console or (as I do it often) return a debug-function which dumps out all the private variables to the console.

这篇关于是否可以访问函数的闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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