-1

I have a question regarding syntax that I've been coming across in JavaScript.

What does it mean if I define functions or variables inside a context like the one just below? (source: http://tutorialzine.com/2010/12/better-confirm-box-jquery-css3/)

(function($) {
  $.confirm = function() {
   ...
  }

  $.confirm.hide = function() {
   ...
  }
})(jQuery);

Also, what the $. mean in the function $.confirm? Also, with $.confirm.hide, I feel that there is some jQuery object involved.

4
  • 1
    I bet this same question has been asked a dozen times in the last week. Commented Jan 28, 2012 at 4:06
  • 1
    JavaScript is like an onion...When you cut into it, it makes you cry. Commented Jan 28, 2012 at 4:24
  • @zzzzBov Onions won't make you cry if you wash it off first. Commented Jan 28, 2012 at 4:37
  • @amnotiam : I am sure its a common question which is why searching for exactly what I wanted was not easy. Sorry if this was spam for you. Commented Jan 28, 2012 at 8:12

4 Answers 4

3

What does it mean if I define functions or variables inside a context like the one just below?

It means that you've defined a function, and ideally prevented global pollution (unfortunately, it wont actually help against global warming). There's a lot going on, so I'll try to split it out into a few parts:

(function($) {
  $.confirm = function() {
   ...
  }

  $.confirm.hide = function() {
   ...
  }
})(jQuery);

Part 1 - Closure

JavaScript is not like most other C-style languages, blocks1 do not get a new variable scope. In many C-style languages, a variable defined within a block will only exist within that block:

Some other C-style pseudo-code

function foo() {
  var a = 1;
  if (somecondition) {
    var b = 2;
    output(a, b); //1, 2
  }
  output(a, b); //throws some sort of exception because 'b' isn't defined.
}

JavaScript:

function foo() {
  var a = 1;
  if (somecondition) {
    var b = 2;
    output(a, b); //1, 2
  }
  output(a, b); //1, 2 due to variable hoisting
}

In JavaScript, variables don't have block scope, instead they have functional scope. Any defined variable is owned by it's first function ancestor. The instantiation of the variable is moved to the top of the function when the script is analyzed (this is called "variable hoisting"), so although you may have written foo (as seen above), what it's actually interpreted as is as follows:

function foo() {
  var a, b;
  a = 1;
  if (somecondition) {
    b = 2;
    output(a, b);
  }
  output(a, b);
}

If there is no parent function of the variable, it's added to the global object, which in web browsers is window:

<script>
var a = 1;
output(window.a); //1 - set because there's no parent function
</script>

functions declared using function [some name]() {...} are treated similarly.

<script>
  function foo() {return 1;}
  output(window.foo()); //1
</script>

If you work on a large project and all variables are defined without a parent function, multiple programmers might use var foo, and would overwrite window.foo, which would lead to buggy and unstable code.

JavaScript allows for the creation of self-executing anonymous functions:

( function (){} )();
-or-
( function () {}() );

This is useful because it creates a new function context with which variables and functions can be defined without polluting the global namespace2. Functions like this that close over a set of variables/functions are called closures.

Parameters can be defined just like any other function, and they are passed to the function in the last set of parens. This explains your first and last lines of code:

(function ($) {
  ...
}(jQuery));

A new function context is created, and jQuery is being passed into the context into the variable $. This is used for aliasing jQuery to the shortcut $, which is a valid character for variable and function names.

Part 2 - Everything's an Object

Everything in JavaScript is an object, except for null and undefined. Mutable objects can have properties and methods set on them. Object literals ({}), array literals ([]), functions (function(){}), and objects created using constructors (new String('foo')) are all mutable objects.

var a = {};
a.foo = 'bar';

function b() {}
b.fizz = 'buzz';

This means that the jQuery object, which is a function, and has been aliased to $, can have new properties added to it:

$.confirm = function () {...};

And after the new $.confirm function is created, $.confirm is an object that can have properties added to it:

$.confirm.hide = function () {...};

If you wanted to call the confirm function outside of the closure, you'd write:

jQuery.confirm();

If you wanted to call the hide function outside of the closure, you'd write:

jQuery.confirm.hide();

1: a block is a section of code contained within {} characters, such as if (...) {/* block region */}, switch() {}, function () {}, while () {}, etc. Don't confuse object literals, which instantiate new objects, with blocks.
2: global namespace pollution is simply adding too many new variables on the global object, which is typically window

Sign up to request clarification or add additional context in comments.

Comments

2

By wrapping a function in parens then executed using to more parents (function() {])(); is a n immediately invoked function. By passing in jQuery within the 2nd set of parens you pass in a paramter which you are you passing in as $.

$.confirm is just a method of the jQuery object

(function($) { // $ = jQuery
  $.confirm = function() {  // <-- set method of jQuery
   ...
  }


  $.confirm.hide = function() { // <-- set method of confirm
   ...
  }

   // usage
  $.confirm();
  // or
  jQuery.confirm();
})(jQuery); // pass in the jQuery object to the function via immediate invocation

Many libraries, like jQuery, use $ as a shortcut variable because it stands out from typical variables used in javascript.

2 Comments

Got a question. Why should I need to define a function as a method of the jQuery object? Why not a simple function? Is there a difference?
Typically, make jQuery plugins that extend the jQuery prototype aka jQuery.fn. Plugins are built for reusability and are often related to jQuery usage. If you had a function that had nothing to do with jQuery functionality then yes, a simple function would make more sense.
1

The code creates an anonymous function and calls it with jQuery as the argument. It's the same as

function addProperties($) {
  $.confirm = function() {
   ...
  }

  $.confirm.hide = function() {
   ...
  }
}
addProperties(jQuery);



$ is a valid variable name in javascript, and the function is adding properties to it. It's the same as:

function addProperties(j) {
  j.confirm = function() {
   ...
  }

  j.confirm.hide = function() {
   ...
  }
}
addProperties(jQuery);



jQuery is an object, and using the dot operator accesses its properties. For example, an object of apple might look like:

var apple = {
    color: 'red',
    height: 55,
    foodType: 'fruit'
};

alert(apple.foodType); // alerts 'fruit'



You might have some misconceptions about jQuery based on your question. jQuery isn't a feature of javascript, it's a library of code that creates a large object called jQuery, though it can also be accessed as $.

Comments

0

The $ is the name of the parameter to the function that is used to create the scope, and because it's called with the jQuery object, $ will be equal to jQuery inside the scope. (By default the global name $ is also assigned jQuery, but this way of using a scope enables you to use $ inside it even if jQUery is used in compatibility mode, where the global $ identifier is not set.)

So, assigning a function to $.confirm will in effect assign it to jQuery.confirm.

As functions are objects in Javascript, you can add properties to them. That's why you can assign a function to $.confirm.hide, which is of course jQuery.confirm.hide.

After that code has run, you can call the jQuery.confirm function, and the jQuery.confirm.hide 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.