我目前正在为JS编写一种插件。我刚刚了解了对象,并且由于我无法访问构造函数中设置的变量(两个或更多级别),我感到很恼火。这就是我的意思:
var myConstructor = function()
{
this.one = "one";
this.two = "two";
this.publicMethod = function()
{
console.log("I can access: ", this.one);
var privateMethod = function()
{
console.log("I cannot access var two like this: ", this.two);
};
privateMethod();
};
};
var myObject = new myConstructor();
myObject.one = 1;
myObject.two = 2;
myObject.publicMethod();
那么,我如何让privateMethod
访问构造函数中设置的变量?与publicMethod使用this
这样做的方式相同。这可能吗?非常感谢你。
答案 0 :(得分:-1)
试试这个。
var myConstructor = function()
{
this.one = "one";
this.two = "two";
this.publicMethod = function()
{
// new variable
_two = this.two;
console.log("I can access: ", this.one);
var privateMethod = function()
{
console.log("I cannot access var two like this: ", _two);
};
privateMethod();
};
};