JavaScript Encapsulation using Anonymous Functions

JavascriptFront End TechnologyObject Oriented Programming

Object-oriented programming languages allow data hiding using private fields. They use these to hide the internals of classes. In JS there is no such in build support to hide/encapsulate the inner workings.

We have Anonymous functions that can give you encapsulation in JS. Let us look at an example −

Example

const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) {
   return (x + y) * HIDDEN_CONST
}
console.log(fnWeWantToHide(1, 2))

If we write the above code out in the open this code will pollute the global namespace with these names. Instead what we can do is wrap this in an IIFE(immediately invoked functional expressions). For Example,

Example

(() => {
const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) {
   return (x + y) * HIDDEN_CONST
}
console.log(fnWeWantToHide(1, 2))
})()

Now, these variables are hidden within the functional expression. But the function and const are no longer polluting the global namespace.

raja
Published on 27-Nov-2019 10:36:45
Advertisements