Chris Middleton
Chris Middleton

Reputation: 5942

Using a function in another function before that first function is defined

When writing an API, I tend to like putting the functions in a top-down order, with the most exposed functions at the top, and the helper functions at the bottom. However, when defining functions with var rather than the magic function delcaration, a function cannot be used before it's defined. So what about if we have an object called $company and we're defining its methods. Can I safely order my JS in this fashion?

var $company = {};

$company.foo = function(x) {
    $company.bar(x*x); // used in definition, but not called directly - ok?
};

// $company.bar(6) // this would produce an error

$company.bar = function(x) {
    alert(x);
};

It seems to work in my current version of Firefox, but I'd like to know if it's defined behavior. Are there any versions of IE where this breaks?

Upvotes: 1

Views: 46

Answers (2)

Nicolas Albert
Nicolas Albert

Reputation: 2596

Yes you can.

Functions are only defined, not executed.

The JS engine executes each line of your file :

var $company = {};
$company.foo = ...;
$company.bar = ...;

And later, at $company.foo execution, $company.bar is defined!

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328724

Yes, this works since no browser (or no JavaScript engine) makes assumptions about what is to the right of a . until it has to evaluate the expression to the left.

But many people don't like this kind of "look ahead" and use callback functions instead:

 $company.foo = function(x, callback) {
      callback(x*x);
 }

This code is more obvious, more flexible since it can call almost anything, you can curry it, etc.

Upvotes: 0

Related Questions