有一种方法可以在javascript中获取对象的范围吗? [英] Is there a way in javascript to get the scope of an object?

查看:123
本文介绍了有一种方法可以在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); });

这篇关于有一种方法可以在javascript中获取对象的范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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