我厌倦了编写长对象属性/方法表达式如下面的示例。逐一添加每个属性似乎需要敲击键盘。
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;
}
}
关于javascript - 添加属性/方法的明确最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28008209/