Nugget 5: JavaScript Function Factory and Closure
A function factory in JavaScript is a function that returns an object. For this Nugget, I created a financial portfolio page to illustrate Function Factory and Closure in JavaScript. I had too much fun doing this.
FinancialStock () is a function factory that creates an equity stock object. Every time this function is invoked, a new object is created. Note that all objects will have the same prototype; they all have the same properties and the same stockFluctuation() calculation function.
When the page is loaded, a new factoryManager() object is created, and when the "Add" button is clicked then the addSymbol() function is invoked and the factoryManager creates a new equity symbol.
The Closure
When a Closure is created in JavaScript, a function can access values outside of its own curly braces, outside of its scope. This happens every time a new equity symbol is created.
Note that createSymbol() has access to the variable indexId which is used as the symbol ID. Every time a new symbol is created indexId is incremented and assigned as the ID of the symbol, and the reason the function remembers the current value of indexId is because of the created Closure. This ID is later used to find the symbol in the array and update the symbol. The Closure is not indexId or function createSymbol(), the Closure has been created for function createSymbol() to have access to the lexical context and access indexId.
This is the entire page code
Comments
Post a Comment