Javascript 添加属性/方法的最佳方式

Javascript 添加属性/方法的最佳方式,javascript,jquery,object,methods,properties,Javascript,Jquery,Object,Methods,Properties,我已经厌倦了编写长对象属性/方法表达式,如下面的示例。一个接一个地添加每一个属性看起来就像是一次键盘敲击 var foo = function(object){ object.foo = "foo"; object.function = function(){}; return object; } 我对它感到非常失望,我想应该有更好的办法。经过一点思考,我能想到的最好的东西就是addProperties循环函数,就像这样 var addPropertie

我已经厌倦了编写长对象属性/方法表达式,如下面的示例。一个接一个地添加每一个属性看起来就像是一次键盘敲击

var foo = function(object){
      object.foo = "foo";
      object.function = function(){};
      return object; 

}
我对它感到非常失望,我想应该有更好的办法。经过一点思考,我能想到的最好的东西就是addProperties循环函数,就像这样

var addProperties = function(properties, subject){
    subject = subject ? subject : {};

    for(propertie in properties){
        if(properties.hasOwnProperty(propertie) && !subject[propertie]){
            subject[propertie] = properties[propertie]
        }
    }
    return subject;
}
这确实使代码更加简洁:

var foo = function(object){
    return addProperties({foo : "foo", function : function(){}}, object); 
}
但是我不满意


因此,我转向堆栈溢出的伟大人物:添加属性/方法的最佳方式是什么?(在您个人看来)

,因为它是用jQuery标记的

var foo = function(obj){
    return $.extend(obj, {
       foo      : "foo",
       function : function(){}
    });
}
也许

var foo = {
    bar: 'bar',
    thatNamedFunction: function(){
        console.log('That named function of foo');
    },
    thatFunctionThatReturnsBar: function() {
        console.log('Returning bar');
        return this.bar;
    },
    thatFunctionThatManipulatesBar: function(newValue) {
        console.log('Bar will now be the newValue')
        this.bar = newValue;
    }
}