【问题标题】:Access inner variables in JavaScript在 JavaScript 中访问内部变量
【发布时间】:2013-02-17 05:02:08
【问题描述】:

我正在为某个网站写userscript。 我需要访问函数中的内部变量。例如,在下面的代码中我需要访问 对象 c 的“私有财产”b

function a(){
    var b;
    //assignment to b and other stuff
};
var c=new a();

我不能更改网站的代码,我只能更改浏览器扩展名SCRIPTISH 并写一个USERSCRIPT。 我的浏览器是最新的firefox。 即使我必须更改Scriptish,我也需要获得访问权限。

【问题讨论】:

  • 您不能直接这样做,将b 分配为this 的属性,它将成为c 的属性。要么,要么附加一个返回b值的方法/函数。 (您必须在构造函数中创建该函数,它也不适用于原型方法)
  • 我认为在这种情况下关闭会有所帮助?不过我可能是错的。
  • 代码不是我的,但我只需要使用 userscript 和 Scriptish 来更改它。我无法将 и 设为全局,它是故意设为本地以防止用户脚本编写的。还有一次:我正在写一个用户脚本。使用 Fiddler 及其脚本引擎也不是好的解决方案。
  • 私有属性是私有的。这就是为什么它们被称为私有的。

标签: javascript properties private gecko


【解决方案1】:

您无法访问函数的内部变量,您应该将其设为全局变量以从外部获取它。

var b;
function a(){
 b=1;
    //assignment to b and other stuff
};
var c=new a();
document.write(c.b);

输出为 1。

【讨论】:

  • 没有。在问题中,函数 a 中的 b 是本地的。你只是在改变全局。将b=1;这一行改成var b=1重新测试。
【解决方案2】:

在您的代码中,b 不是私有变量,而是局部变量。并且在执行var c=new a(); b 之后不再存在。因此,您无法访问它。

但如果你使用closures,一切都会改变:

function a(){
    var b;
    //assignment to b and other stuff
    this.revealB = function() {
        return b;
    }
};
var c = new a();
alert(c.revealB());

这里b仍然是一个局部变量,但是它的生命周期受到闭包的影响,所以当我们调用revealB时它仍然是活着的。

【讨论】:

  • OP 的原始帖子中没有函数revealB - 他无法更改该代码。
【解决方案3】:

做起来很简单,而且非常适合继承应用:

你只需返回你想要的任何东西,也许通过方法返回它,然后在其他函数中重用它并在它的基础上构建。

示例如下:

    function a(){
        var b;
        //assignment to b and other stuff
        return b;
      };

     // or

   function a(){
        var b, result;
        //assignment to b and other stuff
        returnInitial: function() {
           return b;
         }
        // other stuff with b
        return result;
   };

稍后您可以使用所谓的“寄生继承”并使用所有局部变量并添加新方法在其他函数中启动整个函数,如下所示:

var a function() {
        var b, result;
        //assignment to b and other stuff
        returnInitial: function() {
           return b;
         }
        // other stuff with b
        return result;
}
var extendedA function() {
    var base = new a;
    var b = a.returnInitial();
    a.addToB = function (c) {
    var sum = c + a.returnInitial();
    return sum;
    }
}

所以你现在可以得到

var smt = new extendA();
var c = 12; //some number
var sumBC = extendA.addToB(c);

对于这些伟大的实践,我建议 yutube 搜索 doug crockford 的关于 js 对象处理的讲座。

请注意,您需要使用 new,因为如果您不初始化新实例,javascript 使用的动态对象处理可能会使您的原始对象崩溃。

【讨论】:

  • 这不起作用 - 在 OP 的问题中没有返回 b 的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 2013-07-08
  • 2011-08-04
相关资源
最近更新 更多