【问题标题】:Accessing outer scope from inner scope从内部范围访问外部范围
【发布时间】:2016-06-23 01:26:42
【问题描述】:

我有一个看起来有点像这样的类型:

var x = function(){
    this.y = function(){

    }

    this.z = function(){
        ...
        this.A = function(){
            CALLING POINT
        }
    }
}

从调用点开始,我正在尝试调用函数 this.y。我不需要传递任何参数,但是当我从 this.A 设置一些东西时,我需要调用 this.y。

这可能吗?我可以将额外的参数传递给函数以使其成为可能。

【问题讨论】:

  • 这取决于你如何调用你的方法,特别是A
  • @T.J.Crowder 你能澄清一下这不是How to access the correct this / context inside a callback? 的重复吗?它们在我看来是一样的:从外部函数范围访问this 上的属性。
  • @apsillers:我认为那里的代码有很大的不同,OP 不清楚这些答案是如何解决这个设置的。

标签: javascript scope


【解决方案1】:

您可以尝试现代 JavaScript 或 Typescript ()=>,而不是 function()。我也喜欢.bind(this)

【讨论】:

    【解决方案2】:

    这可能吗?

    是的,您可以将this 引用分配给另一个变量,然后在其上调用函数y

    this.z = function() {
        var self = this;
        this.A = function() {
            self.y();
        }
    }
    

    【讨论】:

      【解决方案3】:

      带有bind 的版本,基本上这会为对象添加一个新方法a

      var X = function () {
          this.y = function () {
              document.write('y<br>');
          }
      
          this.z = function () {
              document.write('z<br>');
              this.a = function () {
                  document.write('a<br>');
                  this.y();
              }
          }.bind(this);
      };
      
      var x = new X;
      //x.a(); // does not exist
      x.z();   // z
      x.a();   // a y

      保存内部this的工作示例。

      var X = function () {
          var that = this; // <--
      
          this.y = function () {
              document.write('y<br>');
          }
      
          this.Z = function () {
              document.write('Z<br>');
              this.a = function () {
                  document.write('a<br>');
                  that.y();
              }
          }
      }
      
      var x = new X,
          z = new x.Z; // Z
      
      z.a(); // a y

      【讨论】:

        【解决方案4】:

        您不能因为this.y() 不在this.A() 所在的范围内。如果您将this.y() 设置为全局函数y,则可以:

        var y = function() {};
        var x = function() {
            this.y = y;
            this.z = function() {
               ...
               this.A = function() {
                   this.y(); // will be successful in executing because this.y is set to the y function.
               };
            }
        };
        

        【讨论】:

          猜你喜欢
          • 2011-06-01
          • 2018-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多