0

In this:

somefunction = function() {

    somefunction.method = function() {
         //stuff
    }
//other stuff
}

Is somefunction executed everytime somefunction.method is?

PitaJ
  • 12,969
  • 6
  • 36
  • 55

3 Answers3

3

No, somefunction is executed when you have any of these lines:

somefunction()
somefunction.call()
somefunction.apply()
new somefunction;

somefunction.method() will only execute somefunction.method, but that will have access to variables in the scope of somefunction (as well as its own local variables and all global variables of course).

Paul
  • 139,544
  • 27
  • 275
  • 264
0

Not inherently (unless it is explicitly invoked in the "other stuff"). It is evaluated, but that is only CPU time and not enough to matter.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • What do you mean by evaluated? You mean it's checked for errors? – PitaJ Jun 02 '12 at 02:17
  • @PitaJ: The expression `somefunction` is evaluated. This involves searching for the binding of `somefunction` in all applicable scopes. The function is not invoked. – icktoofay Jun 02 '12 at 02:40
0

No. However you are creating a new closure each time somefunction is called. If somefunction relies on any variables outside of its scope, then the somefunction.method may change depending on when somefunction is called, thus creating a race condition (never fun to debug).

This is probably not the right way to approach the problem.

Consider

somefunction = function() {
  // constructor
}


somefunction.prototype.method = function() {
  //stuff
}
Andy Jones
  • 6,205
  • 4
  • 31
  • 47