简体   繁体   中英

How to access outer object property with inner object function 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.

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;
            }
        } 
    }
})();
var outer = {
    prop : 'prop',
    func : function(){
      return this.prop;
    },
    inner : {
      func : function(){
        return outer.prop;
      }
    }
  }

You can use a reference to outer to access props. For example:

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

console.log(outer.func())  // prop
console.log(outer.test())  // true
console.log(outer.inner.func())  // prop
console.log(outer.inner.test()) // false

https://jsfiddle.net/gk2fegte/2/

When you call this.prop within the inner object this doesn't point to outer but to the inner object. Check out the test function in the above code.

You are using the JavaScript object literal and functions, so that the context of "this" keyword differs. You can see more details about the "this" keyword in How does "this" keyword work within a function? . And in your case, use "outer.prop" to access

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