javascript中对象定义中的对象括号表示法

时间:2014-12-28 13:50:19

标签: javascript object notation object-literal

var events = {
                addEvent: function(element, type, fn, capture){
                     element.addEventListener(type, fn, capture);
                },
                removeEvent: function(){
                     element.removeEventListener(type, fn, capture);
                }
           }

我在对象文字定义中使用这样的东西来减少代码 事件对象只是一个例子

           var events = {
                            [action + "Event"]: function(element, type, fn, capture){
                                  element[action + "eventListener"](type, fn, capture);
                        }
                }
           }

我知道还有其他选项,比如

element.events.add(....) , element.events.remove(....)

或此选项

element.events("add", type, fn, capture) / element.events("remove", type, fn, capture)

1 个答案:

答案 0 :(得分:1)

对象初始值设定项中的属性名称必须是常量。但是,您可以向对象添加属性并动态创建名称:

var events = {
            addEvent: function(element, type, fn, capture){
                 element.addEventListener(type, fn, capture);
            },
            removeEvent: function(){
                 element.removeEventListener(type, fn, capture);
            }
       };

events[action + "Event"] = function() { /* ... */ };