Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulation in JavaScript

Tags:

javascript

A long time ago, I saw someone encapsulate their entire JavaScript block with code something like the code below:

(function() {   // ... })(this); 

Questions:

  1. Is the code above correct?
  2. What benefit is there to encapsulating the entire JavaScript block like denoted above?
like image 765
nickb Avatar asked Aug 29 '10 23:08

nickb


People also ask

Is encapsulation present in JavaScript?

Real Encapsulation in JavaScript Of course, as the functional crowd knows, JavaScript has supported real data encapsulation all along. It's very easy to declare private data in JavaScript.

What is encapsulation and example?

Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. We can create a fully encapsulated class in Java by making all the data members of the class private.

What is the concept of encapsulation?

By definition, encapsulation describes the idea of bundling data and methods that work on that data within one unit, like a class in Java. This concept is also often used to hide the internal representation, or state of an object from the outside. This is called information hiding.

What are the methods for implementing JavaScript encapsulation?

JavaScript encapsulation with closure functions Before the release of JavaScript class syntax, using a closure is the main method to implement encapsulation. Both getName() and setName() functions are closure functions of the createPerson() function. And that's how you implement encapsulation using closures.


2 Answers

Yes, that's correct. It's called a self invoking anonymous function expression.

JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing your code in a self invoking function like the one in your example creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace.

Consider the following:

<html> <body> ... <script>    (function() {        var x = '';        function myFunction () {          alert('Hello: ' + x);       }        x = 'Bob';       myFunction();        alert(typeof x);            // string       alert(typeof myFunction);   // function    })();     alert(typeof x);               // undefined    alert(typeof myFunction);      // undefined </script> <script src="other-javascript.js"></script> </body> </html> 

Whatever you declare in that self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else. The code in other-javascript.js won't see them, for example, and it would be free to declare another function myFunction() without conflicts.

like image 138
Daniel Vassallo Avatar answered Sep 22 '22 23:09

Daniel Vassallo


Also addition to the @Daniel's answer, passing this to the function is a common pattern to have a reference to the global object, for example:

(function(window){  })(this); 

In browser scripting the global object has a property named window which refers to the global object itself, in other environments there is no window property.

Also, another thing that can be done is to specify an argument named undefined, because the undefined property is not described on the ECMAScript 3rd. Edition Standard (there is no guarantee that exist or not), and in some implementations the property is mutable, for example:

(function(window, undefined){  })(this); 

In the above example, we have two local identifiers (which are a bit faster to resolve), window and undefined, only the first one is passed (this, which always refers to the global object in Global code (code that is outside of any function)), and the second, will contain the primitive undefined value, because we are not passing any value to it.

That pattern is used by some libraries like jQuery.

like image 28
Christian C. Salvadó Avatar answered Sep 21 '22 23:09

Christian C. Salvadó