Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access outer object property with inner object function Javascript

Tags:

javascript

I am learning about this keyword in Javascript. I am trying a way to access an outer object property with the inner object function. For example :

var outer = {
    prop : 'prop',
    func : function(){
      return this.prop;
    },
    inner : {
      func : function(){
        return this.prop;
      }
    }
  }
  --> outer.func() : 'prop'
  --> outer.inner.func() : undefined

I understand why it doesn't work but I don't know how to access the prop of the outer object.

like image 748
Phi Nguyen Avatar asked Jun 07 '15 15:06

Phi Nguyen


People also ask

How do you access the outer function of variables in the inner function?

By simply changing the names of "inner" variable to y and the "_inner" variable to z you will get your expected results.

How do you access outer this in JavaScript?

You can bind the "outer" instance to the "inner" function by invoking the bind method on the inner function. Learn more at MDN. Or use an arrow function. I see you answered in 2016 so that should be an option.

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .


1 Answers

It's usually a very bad idea to have the insides of a function property know anything about the variable name that has been assigned to the object that contains that property. It introduces unwanted dependencies and more importantly prevents more than one instance of such an object from existing.

An alternate construct is the "module pattern" show below, using a closure and a variable that allows any nested properties to access that (local) variable.

var outer = (function() {
    var prop = 'prop';
    return {
        prop: prop,
        func: function() {
            return prop;
        },
        inner : {
            func : function() {
                return prop;
            }
        } 
    }
})();
like image 192
Alnitak Avatar answered Nov 14 '22 22:11

Alnitak