-1

我目前正在用 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执行此操作。这可能吗?非常感谢。

4

1 回答 1

-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();
            };
         };
于 2015-01-20T01:38:39.903 回答