質問
連想配列で値をオーバーライドするエレガントな方法を探しています。
たとえば、基本オプションがあるとします。
var base_options = {
hintText:"something",
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
width: 200, height: LABEL_HEIGHT-4,
font: {fontSize:16}, left: 95
}
これをベースとして使用したいのですが、ケースバイケースでこのベースのいくつかのアイテムをオーバーライドすることができます。たとえば、ヒントテキストは各アイテムで異なります。いくつかのパラメーターを変更したこの配列のコピーを取得するためのクリーンでエレガントな方法は何ですか?
次のように、個々のアイテムを変更できることに気付きます。
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)
以上です。 1つの利点は、それがあるからです 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);
それはやり過ぎのように思えるかもしれませんが、すべての新しいインスタンスを配列に追加し、それらを変更する/必要なときにそれらのループを使用することができます。
所属していません StackOverflow