我有一个变量和一个函数
var a=[];
function b(){}
我想让它们在构造函数及其原型中可访问。
function Fnctn()
{
//a and b is accessible here
}
Fnctn.prototype={
one:function()
{
//a and b is accessible here
},
two:function()
{
//a and b is accessible here
},
…
n:function()
{
//a and b is accessible here
}
}
//a and b is not accessible to the user
我发现的第一个解决方案是在构造函数
中使用特权成员function Fnctn()
{
var a=[];
function b(){}
this.a=a;
this.b=b;
}
现在可以使用this.a和this.b在原型中访问a和b,但用户也可以访问它们。 我发现的第二个解决方案是
function Fnctn()
{
var a=[];
function b(){}
//a and b is accessible here
this.one=function()
{
//a and b is accessible here
};
this.two=function()
{
//a and b is accessible here
};
…
this.n=function()
{
//a and b is accessible here
};
}
//a and b is not accessible to the user
这个解决方案做了我想要的,但正如here中所述,它需要更多的内存和时间。因此,这两种解决方案并不合适。 那么,我该怎么做呢? 重新提出这个问题:我想知道是否还有其他方式(如果是,那么是什么)可以做到这一点还是这是唯一的方法? 我想了解任何第三种方法(如果有的话)。
注意:var a不限于Array。它可以是任何东西(字符串,数字等)。