Книга: Functional Programming in JavaScript
Назад: Scope resolutions
Дальше: Gotchas

Closures

One problem with this scope structure is that it leaves no room for private variables. Consider the following code snippet:

var name = 'Ford Focus'; var year = '2006'; var millage = 123456; function getMillage(){   return millage; } function updateMillage(n) {   millage = n; }

These variables and functions are global, which means it would be too easy for code later down the program to accidentally overwrite them. One solution would be to encapsulate them into a function and call that function immediately after defining it.

var car = function(){   var name = 'Ford Focus';   var year = '2006';   var millage = 123456;   function getMillage(){     return Millage;   }   function updateMillage(n) {     millage = n;   } }();

Nothing is happening outside the function, so we ought to discard the function name by making it anonymous.

(function(){   var name = 'Ford Focus';   var year = '2006';   var millage = 123456;   function getMillage(){     return millage;   }   function updateMillage(n) {     millage = n;   } })();

To make the functions and available outside the anonymous function, we'll need to return them in an object literal as shown in the following code snippet:

var car = function(){   var name = 'Ford Focus';   var year = '2006';   var millage = 123456;   return {     getMillage: function(){       return millage;     },     updateMillage: function(n) {       millage = n;     }   } }(); console.log( car.getMillage() ); // works console.log( car.updateMillage(n) ); // also works console.log( car.millage ); // undefined

This gives us pseudo-private variables, but the problems don't stop there. The following section explores more issues with variable scope in JavaScript.

Назад: Scope resolutions
Дальше: Gotchas

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)