题
我正在寻找一种优雅的方式来覆盖关联阵列中的价值。
例如,说我的基本选择为:
var base_options = {
hintText:"something",
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
width: 200, height: LABEL_HEIGHT-4,
font: {fontSize:16}, left: 95
}
我想将其用作基础,但是能够以情况为基础在此基础上覆盖一些项目 - 例如,每个项目的hinttext都不同。什么是一种干净,优雅的方式来获取此数组的副本,并修改了一些参数?
我意识到我可以更改每个单独的项目,如:
options.hintText = "new thing";
但是我怀疑有一种更优雅的方式。
解决方案
您可以使用基类来封装韦斯顿提出的行为。
function Options(changed_options) {
this.hintText = "something";
this.borderStyle =Titanium.UI.INPUT_BORDERSTYLE_ROUNDED;
// ...
if(changed_options)
for(var prop in changed_options)
this[prop] = changed_options[prop];
}
var foo = new Options({ "hintText":"changed"});
应该管用。
其他提示
我已经在我的一些项目中实现了此功能:
if (typeof Object.merge !== 'function') {
Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another
for(var i in o2) { o1[i] = o2[i]; }
return o1;
};
}
因此,现在我可以像以下方式一样使用它:
Object.merge(options, {hintText: "new thing", left: 55});
至于复制对象,已经有一个很好 Stackoverflow讨论 关于那个。
这样的东西?
var changed_options = {
hintText: "somethingElse",
font: {fontSize: 24}
}
for(var prop in changed_options)
base_options[prop] = changed_options[prop];
function merge(base, options) {
var result = {};
for (var k in base) if (base.hasOwnProperty(k)) {
result[k] = options[k] || base[k];
} // note, it will leave out properties that are in options, but not in base..
return result;
}
如果您碰巧使用jQuery,它具有内置 extend
执行此操作的jQuery对象的方法。
您可以使用对象的原型来建立继承,例如:
function inherited_object(extra_properties){
for(var i in extra_properties){
this[i] = extra_properties[i];
}
}
function inherit_from(parent, extra_properties){
inherited_object.prototype = parent;
var obj = new inherited_object(extra_properties || {});
inherited_object.prototype = null;
return obj;
}
然后,如果您有一些对象 A
你只是打电话 B = inherit_from(A, B_stuff)
就是这样。一个优点是,因为 A
是原型 B
, ,对 A
反映 B
.
var base_options = function() {
hintText:arguments[0],
borderStyle:arguments[1],
width:arguments[2],
height:arguments[3],
font:arguments[4]
left:arguments[5]
};
var thisObj = new base_option(blah, blah, blah, blah, blah);
这似乎是过分的,但是您可以将所有新实例添加到数组中,并在需要/需要更改它们时为它们使用for loop。
不隶属于 StackOverflow