添加属性/方法的明确最佳方法
Definitive best way to add properties/methods
我厌倦了编写长对象属性/方法表达式,如下所示。逐个添加每个属性似乎就像是一腰的击键。
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(){}
});
}
相关文章:
- 有条件更新d3.js力图中节点的最佳方法
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 从数组中删除元素的最佳方法是:javascript/jquery
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 列出没有 mysql 的元素的最佳方法是什么
- 在jquery库中重新定义方法的最佳方法
- Javascript,用vars创建对象的最佳方法
- 使用 jQuery 从 HTML 中获取某些值的最佳方法
- 在变量中保存值的最佳方法是在应用程序关闭后使用,然后使用apachecordova在android中重新启动
- 在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法是什么
- 用jasmine测试JavaScriptUI的最佳方法
- 使用javascript:在没有阻止html标记(<b>、<p>等)的情况下,阻止脚本的最佳方法
- 如果我返回表,检查 Ajax 调用是否为 200 OK的最佳方法是什么
- JavaScript - 创建可链接函数时的最佳方法是什么
- 在上下文菜单项单击上显示侧边栏/弹出窗口的最佳方法是什么
- 在 JavaScript 中获取范围的随机数的最佳方法
- 在对象类上实现 jquery 作用域的最佳方法
- 将同步函数包装到承诺中的最佳方法是什么?