Today I Learned - Rocky Kev

TIL a Closure example with class-like methods

POSTED ON:

TAGS:

  1. 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());
  1. 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());
  1. 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:


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.