使对象变量可以在所有"更深层次#34;范围

时间:2015-01-20 01:22:49

标签: javascript object this private-functions

我目前正在为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这样做的方式相同。这可能吗?非常感谢你。

1 个答案:

答案 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();
            };
         };