使对象变量可以在所有 "deeper" 范围内访问

Make object variables be accesible within all "deeper" scope

我目前正在用 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();
            };
         };