简体   繁体   English

如何从内部函数访问外部作用域?

[英]How to access outer scope from inner function?

How can I access container.a from the inner function c1 ? 如何从内部函数c1访问container.a?

var container = {
    a : 'blah',
    b : function(){
        console.log(this.a); // prints 'blah'
    },
    c : {        
        // how to access container.a from here?
        c1: function(){
            // and here?
        }
    }
}

Just refer to container it's a closure 只要参考容器就可以了

var container = {
    a : 'blah',
    b : function(){
        console.log(this.a); // prints 'blah'
    },
    c : {        
        c1: function(){
            console.log(container.a)
        }
    }
}

By name: 按名字:

var container = {
  a : 'blah',
  b : function(){
    console.log(this.a); // prints 'blah'
  },
  c : {        
    // how to access container.a from here?
    c1: function(){
      console.log(container.a);
        // and here?
    }
  }  
}

You can refer to the outer variable that holds a reference to the object, but that's not necessarily stable. 可以参考保存对象的引用外部变量,但不一定稳定。 If the value of "container" is changed, it won't work. 如果更改“容器”的值,它将不起作用。 To prevent that, you can encapsulate the object definition in an anonymous function: 为了防止这种情况,您可以将对象定义封装在匿名函数中:

var container = function() {
  var obj = {
    a : 'blah',
    b : function(){
      console.log(this.a); // prints 'blah'
    },
    c : {        
      c1: function(){
        console.log(obj.a)
      }
    }
  };

  return obj;
}();

That looks very similar, but by doing this you're guaranteed that the value of "obj" won't change (unless some other function in the object changes it, which would be a weird thing to do). 看起来非常相似,但通过这样做,你可以保证“obj”的值不会改变(除非对象中的某些其他函数改变它,这将是一件奇怪的事情)。 Now, no matter what happens to the object originally assigned to "container", that .c.c1() function will continue to work. 现在,无论最初分配给“容器”的对象发生什么,该.c.c1()函数都将继续工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM