我目前正在用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
相同的方式执行此操作。这可能吗?谢谢。
试试这个。
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();
};
};