开发者

Empty Function use in Javascript

开发者 https://www.devze.com 2023-02-21 21:05 出处:网络
I am trying to understand a third party Javascr开发者_JAVA百科ipt code. But am not able to figure out what is the use of the below coding style.

I am trying to understand a third party Javascr开发者_JAVA百科ipt 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,


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);


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.


A function is an object, there's nothing inherently wrong with using it the way it's been used. However, since the function isn't actually used as a function, it would be better to use an Object. You could also use an Array (which is an object), but the same advice applies.

Also, identifiers starting with a capital letter are, by convention, reserved for constructors (unless they are all capitals, which are, by convention, for constants) so use a name starting with a lower-case letter.

0

精彩评论

暂无评论...
验证码 换一张
取 消