Search code examples
javascriptfunctionobjectparents

accessing identifiers from an extra level higher in javascript?


I am working on a project in JavaScript and I need to be able to access a pedant object's variables, that was created with a constructor function from within an function in a child object.

var myObject = function(){
   this.foo = 'stuff',
   this.bar = {
      bit: 'things',
      bite: function(){
         return this.this.foo;
      }
   }
}

var test = new myObject();
test.foo = 'blarg'

test.bar.bite() //<-- this should return 'blarg'

I'm rather lost at this point. I'd prefer to have as little bloatware as possible in this particular application. less because I'm limited in space, but more because I just don't like needlessly large things. And I like to understand everything I implement instead of blindly utilizing JS plugins and libraries.

EDIT: what I want is to have a template that holds a function within an object that references information from another variable within each instance of that template.


Solution

  • You can access the parent level properties on the object by keeping a reference to the current instance of myObject. See the snippet below for an example.

    (function() {
      'use strict';
      
      var log;
    
      var myObject = function myObject() {
        var self = this;
    
        this.foo = 'test';
        this.bar = {
          baz: function baz() {
            return self.foo;
          }
        };
      };
      
      document.addEventListener('DOMContentLoaded', function() {
        log = document.querySelector('#log');
        
        var test = new myObject();
        
        writeLog('test.foo before change');
        writeLog('===============================');
        writeLog(test.foo);
        
        test.foo = 'foo was changed.';
        
        writeLog('Value of test.bar.baz() after change');
        writeLog('============================');
        writeLog(test.bar.baz());
      });
      
      
      function writeLog(text) {
        if (log.innerHTML) {
          log.innerHTML += '<br />' + text;
        } else {
          log.innerHTML += text;
        }
      }
    })();
    <div id="log">
    </div>