【问题标题】:How to access from 'private method' to 'public variable', in Javascript class如何在 Javascript 类中从“私有方法”访问“公共变量”
【发布时间】:2013-10-08 11:31:51
【问题描述】:

首先,请看我的代码。

function test(){

    this.item = 'string';

    this.exec = function(){
        something();
    }

    function something(){
        console.log(this.item);
        console.log('string');
    }
}

我创建了类并调用了'exec function',就像这段代码

var t = new test();

t.exec();

但结果是……

undefined
string

我想从某个函数访问 test.item。

你有什么解决办法吗?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您需要使用apply 调用something,以便在something 中正确设置this:

    function test(){
    
        this.item = 'string';
    
        this.exec = function(){
            something.apply(this);
        }
    
        function something(){
            console.log(this.item);
            console.log('string');
        }
    }
    

    正如@aaronfay 指出的那样,这是因为this 没有引用new test() 创建的对象。你可以阅读更多关于它的信息here,但一般规则是:

    如果在object 上调用函数,则this 指的是object。如果一个函数被自己调用(就像你的代码中的情况),那么this 指的是全局对象,在浏览器中是window。

    【讨论】:

    • 值得注意的是function something() {} 改变了this 关键字的上下文,这就是为什么它不再像预期的那样。 apply 有效地将this 的上下文“应用”到另一个函数。
    • 想象一下!谢谢@go-oleg
    【解决方案2】:

    你有很多选择,但我推荐最后一个。

    var item = 'string'
    

    或

    this.exec = function(){
        something.apply(this, []);
    }
    

    或

    var that = this;
    function something(){
        console.log(that.item);
        console.log('string');
    }
    

    【讨论】:

      【解决方案3】:

      something() 中的this.item 不是你想的那样。

      this 值不同。在这种情况下,它是全局对象。

      在我看来,最好的解决方案是声明一个引用 this 的变量,该变量可以在内部函数内部访问。


      function test() {
          var that = this; // a reference to 'this'
      
          function something() {
              console.log(that.item); // using the outer 'this'
              console.log('string');
          }
      
          this.item = 'string';
      
          this.exec = function(){
              something();
          }
      }
      

      【讨论】:

      • 好的,我知道。那有另一个范围,是的。但是,我不想像'var that = this;'那样使用。无论如何,感谢您的回答! @乔西蒙斯
      • 不客气。我会说使用var that = this; 在大型应用程序中更加动态且易于键入。我是一个类似于 jQuery 的 JS 库的创建者,所以我知道。
      • 这很有帮助。我将在下一个项目中使用它!再次感谢! @乔西蒙斯
      • 不客气。如果您的项目有任何问题,请 PM 我 :)
      【解决方案4】:

      为什么不直接定义这样的东西:

      Fiddle

      function test(){
      
          this.item = 'string';
      
          this.exec = function(){
              this.something();
          }
      
          this.something = function(){
              console.log(this.item);
              console.log('string');
          }
      } 
      
      var t = new test();
      t.exec();
      // output:
      // string 
      // string
      

      【讨论】:

      猜你喜欢
      • 2011-02-11
      • 2012-05-29
      • 2010-10-13
      • 2013-08-03
      • 1970-01-01
      • 2013-05-03
      • 2011-12-03
      • 1970-01-01
      • 2014-10-06
      相关资源
      最近更新 更多