Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope problem nesting Javascript Objects

I am writing some Javascript code using jQuery to display specially formatted widgets in a browser. I've had success, but now I'm working on refactoring my code for two reasons.

(1) I wish to be able to easily use the widget more than once and have a Javascript object referring to each one.
(2) I wish to do it the right way so that my code is totally reusable and doesn't little the global namespace with all sorts of objects and functions.

I'm having a scoping problem and I wish to fix the problem and improve my understanding of Javascript scope. I've condensed this problem down to a tiny code snippet that illustrates what I'm doing:

  function getMyObject() {
      var theObject = {
          doThis: function () { },
          doThat: function () { },
          combinations: {
              doThisTwice: function () { doThis(); doThis(); },
              doThatTwice: function () { doThat(); doThat(); }
          }
      };
      return theObject;
  }

  var myObject = getMyObject();
  myObject.combinations.doThisTwice();

I've declared a function that returns an object.

However, when I try to execute the function combinations.doThisTwice(), the program throws an error saying that doThis() is out of scope. How do I refer to the function doThis in the scope of combinations.doThisTwice?

Update: Thank you kindly for the answer to my question: Replace doThis() with theObject.doThis() inside the function doThisTwice(). This works, but I don't understand why.

I would have thought that the name theObject would not be valid until the end of the object declaration. I think I must misunderstand some fundamental aspect of Javascript... probably because of the C-like syntax.

like image 287
Vivian River Avatar asked Jan 17 '26 01:01

Vivian River


1 Answers

You need to do:

function getMyObject() {
    var theObject = {
        doThis: function () { },
        doThat: function () { },
        combinations: {
            doThisTwice: function () { theObject.doThis(); theObject.doThis(); },
            doThatTwice: function () { theObject.doThat(); theObject.doThat(); }
        }
    };
    return theObject;
}

var myObject = getMyObject(); myObject.combinations.doThisTwice();

You reference 'theObject' from an outer scope to call the functions in an inner object.

like image 175
John Kalberer Avatar answered Jan 19 '26 17:01

John Kalberer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!