0

There are several ways to reach the same end point in JS, for example:

(function (foo, bar) {
  return {run: function () {return foo(bar);}};
} (foo, bar));

(function (foo, bar) {
  return (function(foo, bar) { return {run: function () { return foo(bar); }}} (foo, bar))
} (foo, bar))

(function (foo, bar) {
  var Fizz = function (foo, bar)  { this.run = function () { return foo(bar); }; };
  return new Fizz(foo, bar) 
} (foo, bar))

Now for these, I know that one difference is that the prototype in the third case for the returned object would be different, but other than that, all three paths lead to an object which provides the same api. And since Javascript is a duct typed language, what a thing is is usually defined by its behavior.

Are there any other implications of choosing any one approach of the three that I am ignoring ?

1 Answer 1

1

The only difference between the first two is the depth of the stack(though it's not outright impossible to optimize that away), since the only difference is the amount of scopes you are creating. Notice that you can continue creating as many scopes as you whim:

(function (foo, bar) {
        return (function(foo, bar) {
                return (function(foo, bar) {
                        return (function(foo, bar) {
                                return (function(foo, bar) {
                                        return (function(foo, bar) {
                                                return {run: function () { return foo(bar); }}
                                        } (foo, bar))
                                } (foo, bar))
                        } (foo, bar))
                } (foo, bar))
        } (foo, bar))
} (foo, bar))

Behind the scenes, a JavaScript function keeps a pointer to it's lexical scope, so the more scopes you create the more deep you'll have to go up in the scope of the function you put in the run field of the object. Again, this might be optimized away and has no effect on the logic since JavaScript function objects do not provide you with a way to access that scope(though a JavaScript implementation might add such a field)

1
  • this seems complicated ..:o May 26, 2014 at 4:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.