aceminer
aceminer

Reputation: 4295

undefined function in the same js file

define(function() {
  return {
    show: function(msg) {
      alert(msg);
    },
    showing: function(msg) {
      adding(10); //it throws up an exception saying that adding is undefined.
    },
    adding: function(x) {
      return x + 10;
    }
  };
});

I have tried to switch adding above the showing function but it doesnt seem to work as well. Am i misunderstanding something? I am still very new to require js.

Upvotes: 0

Views: 203

Answers (3)

ventaur
ventaur

Reputation: 1851

This is more of an issue with the JavaScript prototypical language than Require. It's a matter of the adding function's scope. Try this to get it working, then I suggest you look quite a bit into scoping with JS.

define(function() {
  function addTenTo(x) {
    return x + 10;
  }

  return { 
    show: function(msg) {
        alert(msg);
    },

    showing: function(msg) {
        return addTenTo(10);
    },

    adding: addTenTo   // as suggested by gp
  };

});

Upvotes: 2

Aleksandr
Aleksandr

Reputation: 2331

Your adding function is not in a scope of showing. Basically adding is just a property of object, not the function name which can be called.

this.adding(10);

So, we are calling adding as an Object property inside of the Object scope (that is why we are using this keyword)

Upvotes: 1

gp.
gp.

Reputation: 8225

Call adding with this.

showing: function(msg) {
  this.adding(10);
}

this will refer to the object you are returning which defines showing and adding methods.

Upvotes: 2

Related Questions