如果没有定义对象,则对象默认为函数
假设我有以下对象:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数也是对象,因此您可以为其分配属性:
更新:(根据要求)
如果您不想一遍又一遍地编写
Fxy.commands.group
(这实际上并没有那么糟糕,因为它清楚地表明了函数分配到的位置),您可以创建一个复制属性的函数(例如jQuery.extend
)。这是一个非常基本的版本:然后你可以这样做:
Functions are objects too, so you can assign properties to them:
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 (likejQuery.extend
). Here a very basic version:Then you can do: