在javascript中从类外部访问对象的私有成员
我定义了这样一个类:在javascript中从类外部访问对象的私有成员,javascript,Javascript,我定义了这样一个类: function Class1(){ function Func1(){ /* Methods and vars */ }; Funcs = new Array(); this.appendAction = new function(ArgFunc){ Funcs.push(ArgFunc); }; }; Object1 = new Class1(); function OutFunc(){ /* Defi
function Class1(){
function Func1(){
/* Methods and vars */
};
Funcs = new Array();
this.appendAction = new function(ArgFunc){
Funcs.push(ArgFunc);
};
};
Object1 = new Class1();
function OutFunc(){
/* Defining commands here */
};
Object1.appendAction(OutFunc);
我的问题是,是否有办法访问函数OutFunc()范围内的Object1的私有成员,比如Func1(),因为该函数现在是Object1的数组Funcs的一个元素。这有点奇怪,但只需对代码稍加修改,我就会这样做:
function Class1(){
function Func1(){
/* Methods and vars */
};
Funcs = new Array();
this.appendAction = new function(ArgFunc){
Funcs.push(function() { return ArgFunc(Func1); });
};
};
Object1 = new Class1();
function OutFunc(func1){
/* Defining commands here */
func1();
};
Object1.appendAction(OutFunc);
但实际上,这可能不是解决问题的好方法。为什么要访问外部函数的私有变量?你考虑过定位器和吸气剂吗?这是最好的替代方案好吧,假设该类是库中定义的函数的处理程序,因此这些函数会被进一步处理,但不会自动执行。无论如何,我想知道是否有可能以这种方式访问类的元素,而不需要对类1进行任何额外的修复或重新排列。是的,无论如何,我可以这样做。嗯。。。如果您能够修改Class1,为什么不将Func1设置为“public”,只需添加:this.Func1=Func1。在函数Class1()中。这不会破坏任何代码