Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty Function use in Javascript

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,

like image 807
duskandawn Avatar asked Apr 05 '11 01:04

duskandawn


People also ask

How do you define an empty function?

An empty function is basically creating a function without defining any operations inside it. A class named Demo contains an empty function named 'my_empty_fun' which is just completed by placing two flower brackets, without adding any functionality into it.

What is empty JavaScript array?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

Is empty in JS?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

How check if object is empty JavaScript?

Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.


2 Answers

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);
like image 86
Travis Webb Avatar answered Nov 07 '22 04:11

Travis Webb


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.

like image 28
SLaks Avatar answered Nov 07 '22 03:11

SLaks