Unable to access another object in javascript

81 views Asked by At

I have uploaded a sample code where there are two objects defined using the modular pattern.

var obj1 = {
    cachdom: function() {
      // querying a dom element
      this.$interactiveReport = $('#BugPreventiveIR_data_panel');

      }
    };

    var obj2 = {
      $IR: obj1.$interactiveReport,
      logging: function() {
        // This returns undefined
        console.log(this.$IR);
      }
    };

    // Invoking the Objects only after document is ready.
    $(document).ready(function() {
      console.clear();
      interactiveReportRegion.init();
      displayOfBugList.logging();
    });

However, when I check in console the obj2.logging returns undefined for this.$IR. However, if I were to access obj1.$interactiveReport through console I can view the object values. Similairly, if I were to define the second object in the console again, it obtains the correct value for obj2.$IR.

Any reason I am unable to access the first object's properties in the second object?

My entire code can be found here https://gist.github.com/alaghu/6225e50b35ecfdaf2ee8f752f596f49b

2

There are 2 answers

3
I wrestled a bear once. On

The logging function needs to know what "this" means since it's not a constructed object.. this should do it.

displayOfBugList.logging.apply(displayOfBugList);
2
Sir Pat On

defining a function changes the scope for "this". Consider using lamda functions to fix this. There is also the ability to bind what "this" is but I shy away from that method