Empty Function use in Javascript
Solution 1
They are creating a namespace. There are many ways to do this, and all are more-or-less equivalent:
A = {
Prop : '23',
generate : function (n) {
// do something
}
};
Or, equivalently:
A = { };
A.Prop = '23';
A.generate = function (n) {
// do something
};
Also, if you like being verbose:
A = new Object();
A.Prop = '23';
A.generate = function (n) {
// do something
};
function
is usually used to denote a "class" rather than a "namespace", like so:
A = (function () {
var propValue = '23'; // class local variable
return {
"Prop" : propValue,
"generate" : function (n) {
// do something
}
};
})();
// then I can use A in the same way as before:
A.generate(name);
Solution 2
It looks like they're using a dummy function to create a namespace.
You're right; this is useless.
They should use a normal object instead.
duskandawn
Updated on June 07, 2022Comments
-
duskandawn about 2 years
I am trying to understand a third party Javascript code. But am not able to figure out what is the use of the below coding style.
function A(){ } A.Prop = '23'; A.generate = function(n){ // do something }
And then it is just used as :
A.generate(name);
Can someone explain what this code is doing. I understand some bit of OO Javascript, but i wonder if this is any other form of extending an object with new properties to it. Though i dont see any "new" keyword being used, to create an object.
Any ideas ?
Thanks,
-
duskandawn about 13 yearsThanks, for the answer, i was thinking on the same lines. But do you know will there be any performance issue, using this coding style. I mean to say is this a general way to create namespaces. I would assume
code
var A = new function(){}();code
to do something like this, if i dont touch the whole codebase ? -
SLaks about 13 yearsThe correct way to create a namespace is to use an object literal:
var a = { };
. -
Andrew over 11 yearsUnless they want to support "instances" of that object, right? function A(){} allows for the
var a = new A();
pattern, I think. -
SLaks over 11 years@Andrew: But they're not making a class.
-
Andrew over 11 years@SLaks, what specifically makes you sure of that?
-
SLaks over 11 years@Andrew: They're only using it as a namespace.
-
Andrew over 11 years@SLaks: Isn't that assuming the conclusion? How do you know that's being used as a namespace without more context?
-
ncubica about 11 yearswell you should read this book for more professional patterns addyosmani.com/resources/essentialjsdesignpatterns/book