我正在为某个网站编写用户脚本。我需要访问函数中的内部变量。例如,在以下代码中,我需要访问对象 c 的“私有财产”b
function a(){
var b;
//assignment to b and other stuff
};
var c=new a();
我不能更改站点的代码,我只能更改 BORWSER 扩展脚本并编写用户脚本。我的浏览器是最新的firefox。即使我必须更改Scriptish ,我也需要获得访问权限。
您无法访问函数的内部变量,您应该将其设为全局变量以从外部获取它。
var b;
function a(){
b=1;
//assignment to b and other stuff
};
var c=new a();
document.write(c.b);
输出将为 1。
这很简单,非常适合继承应用程序:
您只需返回您想要的任何内容,并且可能通过方法返回它,然后在其他函数中重用它并在其上构建。
示例如下:
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 使用的动态对象处理可能会使您的原始对象崩溃。
在您的代码b
中不是私有变量,而是局部变量。并且在执行var c=new a();
b 之后不再存在。因此,您无法访问它。
但是如果你使用闭包,一切都会改变:
function a(){
var b;
//assignment to b and other stuff
this.revealB = function() {
return b;
}
};
var c = new a();
alert(c.revealB());
这里b
仍然是一个局部变量,但它的生命周期受到闭包的影响,因此当我们调用revealB
.