Making a module in JS is kind of interesting. Especially, if you expect something like a class like in VBA or C#. Well, it has nothing to do with it, it is just a function, assigned to a variable.
In the current article, I simply make one small module and I print it. The trick is in the nested functions in the module, which return what you have asked for … In a way! đŸ™‚
Thus, I have asked to create two articles, with dates and titles. Then I change the title of the second article (in an array we start counting from zero). Then I print what I have. The interesting thing is that in any other language (C#, VB or anything powered by .Net or Java engine) I would have expected to see two different versions of the array named “articles”. However, in JS this is not the case đŸ™‚
Check out what do I mean here:
Yup, this is how it looks like! đŸ™‚ JS is fast like the wind in its own way!
Here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<!DOCTYPE HTML> <html> <head> </head> <body> <script type="text/javascript"> // Example of modules in JavaScript 'use strict'; var vitoshacademy = (function(){ var articles = []; function letArticles(date, title){ articles.push([date,title]); } function changeArticleTitle(number, newTitle){ articles[number][1] = newTitle; } function getArticles(){ return articles; } function deleteArticles(){ articles = []; } return{ la: letArticles, ga: getArticles, ca: changeArticleTitle, de: deleteArticles }; })(); vitoshacademy.de(); console.log(vitoshacademy.ga()); vitoshacademy.la("12/12/2015","How to code?"); vitoshacademy.la("12/12/2016","How to code even better?"); console.log(vitoshacademy.ga()); vitoshacademy.ca(1,"Changed article title to this"); console.log(vitoshacademy.ga()); </script> </body> </html> |