0

I like to create pretty OO javascript, sometimes with prototype and sometimes more native. In many cases I create javascript classes looking like this

var myObject = myObject || {};

myObject.Example1 = function () {
    "use strict";

    // ctor
    function self() { }

    // init
    self.init = function () {
        console.log("Example 1 did init");
    };

    return self;
};

myObject.Example2 = (function ($) {
    "use strict";

    // ctor
    function self() { }

    // init
    self.init = function () {
        console.log("Example 2 did init");
    };

    return self;
})($);

But I seem to have forgot why I can't create an instance of the function enclosed with () and $.

var obj1 = new myObject.Example1();
obj1.init(); // Does init

var obj2 = new myObject.Example2();
obj2.init(); // Does not init (obj2.init is not a function)

The myObject.Example1() works as expected but why can't I call the myObject.Example2()?

1
  • In the first case you are assigning a function, in the second you are assigning the result of invoking the function with $ as an argument. Commented May 5, 2013 at 20:51

2 Answers 2

2

The correct way to use the pattern ‘make an object from a closure’ would be like this:

myObject.Example2 = (function ($) {
   return function () {
    "use strict";

    // ctor
    function self() { }

    // init
    self.init = function () {
        console.log("Example 2 did init");
    };

    return self;
   }
})($);
Sign up to request clarification or add additional context in comments.

3 Comments

Just to be almost needlessly pedantic (but this is Stackoverflow afterall :-) in this case you don't really need the parentheses around the anonymous function. Because it's on the right side of the = operator, the parser will know unambiguously that it's a function expression.
You are certainly correct from the parser’s point of view. From the human reader’s point of view it’s part of the pattern to make more obvious the intention of invoking the anonymous function and assigning its result.
Yes that's completely fair and I have no problem with the practice.
1

Example2 is the return value of a function that defines a function called self, adds a property to it, and then returns that function.

Example1 has an almost identical function, but since you don't have () at the end, it isn't called, so the value of Example1 is that function and not the function defined inside it.

This has nothing to do with the difference between function () { and function ($) { and everything to do with the difference between }; and })($).

The $ argument is entirely irrelevant since you don't use $ inside the function.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.