有一种方法可以在javascript中获取对象的范围吗?

问题描述:

有没有可以使用的属性或Web工具,所以我可以在运行时评估两个javascript对象的范围?

Are there any properties one can use or web tools so I could evaluate the scope of two javascript objects at runtime?

不在浏览器中犀牛JavaScript平台可以通过(通过Java)对各种范围和上下文进行访问。

Not in a browser. The Rhino JavaScript platform gives you all kind of access to scopes and contexts though (through Java).

您需要访问该范围的目的?

For what purpose do you need to access that scope?

如果要执行一段代码,可以访问特定对象的属性,您可以随时使用 eval (包括其性能缺点)。

If you want to execute a piece of code with access to properties of a certain object, you could always use eval and with (with their performance drawbacks included).

function exec(obj, func) {
   with (obj) {
      eval("("+func+")()");
   }
}

var actObj = {
   annoying: function (txt) {
      alert(txt);
   }
}

// using it:
exec(actObj, function () {
   annoying("HEY THERE FRIEND ! !");
});

如果要在某个内容中执行代码,没有对象,只需在其中定义一个函数可以从外部执行的范围。

If you want to execute code in a certain content, without the object, just define a function inside that scope that you can execute from the outside.

例如:

var module = (function () {
   var a = 2;

   var peek = function (fn) {
      eval("("+fn+")()");
   }

   return {
      peek: peek
   }
})();

module.peek(function () { alert(a); });