最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

namespaces - Empty Function use in Javascript - Stack Overflow

programmeradmin1浏览0评论

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,

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,

Share Improve this question asked Apr 5, 2011 at 1:17 duskandawnduskandawn 6751 gold badge10 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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)

  1. 暂无评论