Question

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?
        }
    }
}
Was it helpful?

Solution 2

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.

OTHER TIPS

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?
    }
  }  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top