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

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

问题描述

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.

但是您可以通过 getter/setter 授予访问权限.

However you could give access via getters/setters.

您可能想看看 Stuart Langridge 的演讲 关于关闭.非常值得推荐的还有 Douglas Crockfords Explanations.你可以用闭包做很多花哨的东西;)

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天全站免登陆