user2204449
user2204449

Reputation:

What's the difference between these two functions in JavaScript?

Type 1 :

var EXAMPLE = function() {};

Type 2:

var EXAMPLE = function($) {
    return {};
}(jQuery);

I'm JavaScript beginner and trying to understand the difference between these two piece of code. In functionality wise I didn't see the difference when I tried to add a property to the EXAMPLE object.

Upvotes: 1

Views: 97

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074285

There are a couple of major differences there:

  1. With the first one, the value of EXAMPLE ends up being a function object. With the second one, it ends up being a plain object (not a function), because in the second one, the function is being called and you're storing its return value (the {}) in EXAMPLE.

  2. The second one relies on your having a jQuery symbol defined (probably as a result of including jQuery on the page). The first doesn't.

So they're pretty different.

The first is a pretty generic way of creating a function (in this case, a function that doesn't do anything).

The second is a fairly standard way to use jQuery without relying on the $ global (because sometimes people use jQuery.noConflict() to release the $ symbol). The idea is that since jQuery is being passed into the function as the $ argument, within the function code can use $ even though there is no $ global. People routinely do this and return an object with functions on it, like this:

jQuery.noConflict(); // Release $
display("typeof $ = " + typeof $);   // "undefined"

var EXAMPLE = function($) {
  return {
    red: function(selector) {
      // Note we can use $ here, even though $ isn't
      // defined globally
      $(selector).css("color", "red");
    },
    green: function(selector) {
      $(selector).css("color", "green");
    }
  };
}(jQuery);

setTimeout(function() {
  EXAMPLE.red("#target");
}, 700);

setTimeout(function() {
  EXAMPLE.green("#target");
}, 1400);

function display(msg) {
  jQuery("<p>").html(String(msg)).appendTo(document.body);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="target">I'm the target element</div>

Upvotes: 8

Krzysiek
Krzysiek

Reputation: 2495

This example create function and assign it to Example

var EXAMPLE = function() {};

This RUN function and assign object returned by function Example = {b: jQuery}

var EXAMPLE = function($) {
    return {b: $};
}(jQuery);

Upvotes: 0

Related Questions