开发者

Object default to a function if no objects within are defined

Let's say I have the following objects:

Fxy.commands={
    group:{
        add:function(msg){

So, of course, Fxy.commands.group.add('s开发者_如何学运维omething') will do whatever that function does. But, what if I call Fxy.commands.group('something')? Well, I honestly don't know how to make it handle that. That's what I'm asking: how would I make an object default to a function if no object within it is called? Obviously the code above won't work because it has no default function as I don't even know where it would be placed. If it is possible, how would it be done? If not, simply say so, but please also suggest a workaround.


Functions are objects too, so you can assign properties to them:

Fxy.commands = {
    group: function(msg) {}
};

Fxy.commands.group.add = function(msg){};

Update: (as requested)

If you don't want to write Fxy.commands.group over and over again (which is actually not that bad, because it makes clear where the functions are assigned to), you could create a function which copies properties (like jQuery.extend). Here a very basic version:

function extend(A, B) {
    for(var prop in B) {
        if(B.hasOwnProperty(prop)) {
            A[prop] = B[prop];
        }
    }
}

Then you can do:

var funcs = {
     add: function(){},
     remove: function(){},
     ...
};

extend(Fxy.commands.group, funcs);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜