添加属性/方法的明确最佳方法

Definitive best way to add properties/methods

本文关键字:方法 最佳 添加 属性      更新时间:2023-09-26

我厌倦了编写长对象属性/方法表达式,如下所示。逐个添加每个属性似乎就像是一腰的击键。

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); 
}

但我不满意!!

所以我转向你,堆栈溢出的伟大人物:添加属性/方法的最终最佳方法是什么? (以您的个人观点)

也许...

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;
    }
}

因为它被jQuery标记

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