-2
\$\begingroup\$

Is there anything functionally different about this prototypical design pattern:

var Greeter = function(message) {
    this.greeting = message;
    return this;
}

Greeter.prototype.greet = function () {
    return "Hellos, " + this.greeting;
}

As opposed to:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hellos, " + this.greeting;
    };
    return Greeter;
}());

The bottom approach seems to be cleaner and so I opt into using that more often, but I have seen many people use the top approach.

\$\endgroup\$
2
  • \$\begingroup\$ Downvote without a comment? \$\endgroup\$
    – Phil
    Commented Jan 18, 2017 at 17:26
  • \$\begingroup\$ This question is just off-topic for the site, as you are asking about opinions on a practice (based on a hypothetical example), rather than about real code. \$\endgroup\$ Commented Jan 19, 2017 at 0:32

1 Answer 1

1
\$\begingroup\$

You will note that the core logic in both examples is pretty much the same. So really the only difference here is whether you allow the function (class) definition to be callable from global scope.

In the second example, wrapping the logic in an IIFE has the effect of hiding the function definition from global scope, in essence providing singleton behavior.

Which you might use could depend on the needs of your application.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.