Encapsulation in JavaScript

JavaScript

In JavaScript, encapsulation is achieved by a a self invoking anonymous function expression.

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

(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

Whatever we declare the self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else and it would be free to declare another function myFunction() without conflicts.

TypeScript

In Typescript we do polymorphism by using three type of modifier Public, private, and protected. Public is default modifier.

Private Modifier
class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

new Animal("Cat").name; // Error: 'name' is private;
Protected Modifier
class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error

results matching ""

    No results matching ""