frequent
frequent

Reputation: 28513

How to correctly reference an method set on an object when declaring a method on this object in Javascript?

Kind of basic I guess. I'm writing on a modular application and am often running into having to do something like this:

var foo = {};

foo.do_something = function () {
  //...
};

foo.do_something_else = function () {
  // ...
};

foo.do_all = function () {
  var x = foo.do_something();

  // ...
};

I prefer to stick with functional programming like this.

Question:
Is it safe to reference methods declared on foo inside the declaration of other methods? Any better idea on how to do this?

Thanks!

Upvotes: 1

Views: 30

Answers (2)

voithos
voithos

Reputation: 70602

You could use the module approach to accomplish the same separation of functionality, but without having to worry about constantly referencing a global name.

var foo = (function() {
  var do_something = function () {
    //...
  };

  var do_something_else = function () {
    // ...
  };

  var do_all = function () {
    // Note: can refer to `do_something` directly.
    var x = do_something();

    // ...
  };
  return {
      do_something: do_something,
      do_something_else: do_something_else,
      do_all: do_all
  };
})();

In general, you can use an IIFE (immediately-invoked function expression) to create a local, private scope in which you can define whatever you need to without having to worry about polluting global scope, and export functions or objects from within as needed.

Upvotes: 1

Giovanni Bitliner
Giovanni Bitliner

Reputation: 2072

That is fine.

You can also use this keyword, that refers to the specific instance. Be careful with this, because during execution the scope can change (because for example you invoke a method of an other object...).

To avoid it a good practice is to set in the first row of the method the assignment var self=this and then you can always use self for referencing the object instance.

Upvotes: 1

Related Questions