I opened a javascript project called Jibberish (https://github.com/mdp/gibberish-aes) and I tried to understand it's coding style, I just give a portion of it's start and end:
(function (root, factory) {
if (typeof exports === 'object') {
// Node.
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals (root is window)
root.GibberishAES = factory();
}
}(this, function () {
'use strict';
var Nr = 14,
/* Default to 256 Bit Encryption */
Nk = 8,
Decrypt = false,
enc_utf8 = function(s)
{
try {
return unescape(encodeURIComponent(s));
}
catch(e) {
throw 'Error on UTF-8 encode';
}
},
//...................................
return {
"size": size,
"h2a":h2a,
"expandKey":expandKey,
"encryptBlock":encryptBlock,
"decryptBlock":decryptBlock,
"Decrypt":Decrypt,
"s2a":s2a,
"rawEncrypt":rawEncrypt,
"rawDecrypt":rawDecrypt,
"dec":dec,
"openSSLKey":openSSLKey,
"a2h":a2h,
"enc":enc,
"Hash":{"MD5":MD5},
"Base64":Base64
};
}));
Just to have an idea of it's usage:
// GibberishAES.enc(string, password)
// Defaults to 256 bit encryption
enc = GibberishAES.enc("This sentence is super secret", "ultra-strong-password");
alert(enc);
GibberishAES.dec(enc, "ultra-strong-password");
I can see an outmost self-executing function returning an object at the end of the code which in fact is anonymous(!) and the members of this object are the functions defined inside the self-executing function so, property "size"
refers to function size()
defined as a function expression:
size = function(newsize){...}
I can even recall all the discussions about private and public functions of such approach by calling all the returned functions as public
and the rest as private
but there are some things that puzzle me a lot:
why the outer anonymous function has arguments and where are they going to be used?
instead of
(function(){//put my code here...}());
author used(function(root, factory){//some code...}(this, function(){//main code here...}));
, why was that?On question (2) I can see two arguments
this
andfunction(){//main code here...}
passed as arguments to the outer anonymous function in place ofroot
andfactory
. So,root
becamethis
! But, now wherethis
is referring to?Maybe we could achieve a better rewrite of all this or not? I just read How do I declare a namespace in JavaScript? and I find Jaco Pretorius answer so great that I can rewrite this one and add it to my namespace like so:
(function(myGibberishAES){
//main code here...
}(window.myGibberishAES = window.myGibberishAES || {}));
Is this ok with acceptable coding standards?
Thanks!