TIL a Closure example with class-like methods
POSTED ON:
TAGS: javascript advanced
- JavaScript allows for the nesting of functions.
const grievous = function a() {
function b() {
return "General Kenobi! You are a bold one.";
}
return b();
}
console.log(grievous());
- It also allows inner functions full access to all the variables and functions defined the outer function (and all other variables and functions that the outer function has access to).
const grievous = function a() {
// outer
const quote = "General Kenobi! You are a bold one.";
function b() {
// inner
const quote = "Back away! I will deal with this Jedi slime myself.";
return quote;
}
return b();
}
console.log(grievous());
- However, the outer function does not have access to the variables and functions defined inside the inner function. A closure is created when the inner function is somehow made available to any scope outside the outer function.
let starWarsCharacter = function(name) {
let title;
return {
// SETTERS
setName: function(newName) {
name = newName;
},
setTitle: function(newTitle) {
title = newTitle;
},
// GETTERS
getName: function() {
return name;
},
getTitle: function() {
return title;
},
}
}
// define the hero
var hero = starWarsCharacter("Luke");
hero.setTitle('Jedi Knight');
console.log(hero.getName()); // Luke
console.log(hero.getTitle()); // jedi Knight
// change the hero
hero.setName("Rey");
console.log(hero.getName()); // Rey
console.log(hero.getTitle()); // Jedi Knight
Notice that function 'saves' the occupation.
REFERENCE:
https://stackoverflow.com/a/31914232/4096078
SERIES:
- Closure The Basics
- Closure Example with class-like methods
- Closure Example with private data
- Closure Example as a backpack
Related TILs
Tagged: javascript