ta4caw
Last Updated: February 25, 2016
·
362
· adam boczek
Ja w hh 2

Using IIFE to create private members in JavaScript

Demonstrates how to use IIFE to create private members in JS.
You will not probably use it to create getter and setter, as in my example.
It is for demonstration purposes only.<br/>
IIFE === Immediately-invoked function expression

var Dog = (function() {
    var name = "defaut name";

    var DogInner = function() {
        this.getName = function() {
            return name;
        };

        this.setName = function(value) {
            name = value;    
        };    
    };

    return DogInner;
})(); // this does the trick

var dog = new Dog();
dog.name = "Frankenweenie";     // has no effect on the name in Dog object
console.log(dog.getName());     // logs: defaut name
dog.setName("Frankenweenie");   
console.log(dog.getName());     // logs: Frankenweenie
Say Thanks
Respond