如果没有定义对象,则对象默认为函数

发布于 2024-11-15 06:24:36 字数 363 浏览 2 评论 0原文

假设我有以下对象:

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

当然,Fxy.commands.group.add('something') 将执行该函数执行的任何操作。但是,如果我调用 Fxy.commands.group('something') 会怎样?好吧,老实说我不知道​​如何让它处理这个问题。这就是我要问的:如果一个对象中没有调用任何对象,我如何使一个对象默认为一个函数?显然上面的代码不起作用,因为它没有默认函数,因为我什至不知道它会放在哪里。如果可以的话,会怎样做呢?如果没有,请简单说明,但也请提出解决方法。

Let's say I have the following objects:

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

So, of course, Fxy.commands.group.add('something') 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┾廆蒐ゝ 2024-11-22 06:24:36

函数也是对象,因此您可以为其分配属性:

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

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

更新:(根据要求)

如果您不想一遍又一遍地编写Fxy.commands.group (这实际上并没有那么糟糕,因为它清楚地表明了函数分配到的位置),您可以创建一个复制属性的函数(例如 jQuery.extend)。这是一个非常基本的版本:

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

然后你可以这样做:

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

extend(Fxy.commands.group, funcs);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文