如何从浏览器控制台访问存储在函数闭包的JavaScript变量? [英] How to access javascript variable stored in function closure from browser console?

查看:343
本文介绍了如何从浏览器控制台访问存储在函数闭包的JavaScript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个全局函数:

Lets say I have a global function:

function Init()
{
       var v = 10;
       window.GlobalFunction = function()
       {
          // Global Function has access to v, because of closure
          alert(v);
       }
}

Init();

我如何从FireBug控制台获得v的值?我可以把断点放在那里,看到价值。然而这对我来说是不够的。我想为第三方网站创建FireFox插件,所以我需要访问此变量,但不能更改源代码。

How I can get value of v from FireBug console? I can put break point there and see value. However this is not enough for me. I want to build FireFox addon for third party website, so I need access this variable, but can't change source code.

推荐答案

如果 v 是一个全局变量,就像你说的,那么你应该能够在控制台输入 v

If v is a global variable like you say, then you should just be able to type v at the console to get its value.

如果 v 不是全局变量,那么您只能从函数中访问它包含它。 JavaScript是一种函数范围语言, var 关键字表示该变量只能在当前范围内访问。如果你不想使用断点/调试器,如果你不能修改源,如果源没有getter方法的变量,你可能是运气不好。

If v is not a global, then you can only access it from within the function that contains it. JavaScript is a function-scope language, and the var keyword indicates that the variable is accessible only within the current scope. If you don't want to use a breakpoint/debugger, if you can't modify the source, and if the source has no getter method for the variable, you may be out of luck.

尝试在这里获得创意,您可以根据 Init 的原型创建一个对象对象包含它(例如,使用 new 关键字),并向您的版本的对象添加一个getter函数。然后使用您的新对象,无论你以前使用原始代码的对象。

Trying to get creative here, you might be able to create an object based on the prototype of Init or whatever object contains it (using, for example, the new keyword) and add a getter function to your version of the object. Then use your new object wherever you were previously using the original code's object.

这篇关于如何从浏览器控制台访问存储在函数闭包的JavaScript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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