1

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!

frequent
  • 27,643
  • 59
  • 181
  • 333
  • Depends on [whether you use `this` or `foo`](http://stackoverflow.com/q/10711064/1048572) to refer to your object. If the object is an "instance" and has "methods" though, that is not very functional - better see `foo` as a namespace for your functions (and use it as such). – Bergi Nov 11 '14 at 22:28

2 Answers2

1

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.

Giovanni Bitliner
  • 2,032
  • 5
  • 31
  • 50
1

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.

voithos
  • 68,482
  • 12
  • 101
  • 116