简体   繁体   中英

How to access outer scope from inner function?

How can I access container.a from the inner function c1 ?

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). Now, no matter what happens to the object originally assigned to "container", that .c.c1() function will continue to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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