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
Written by Adam Boczek
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#