2011-07-05 9 views
0

私はこれらのプロパティが静的なJavaScriptオブジェクトを持っています。彼らは建設時に決定することができます。しかし、オブジェクトの状態を変更するメソッド "morph"も追加しました。だから、これらのプロパティはそれと共に変化するはずです。オブジェクトプロパティの更新をどのようにリファクタリングしますか?

私は以下のメソッド(longNameMethod、問題なし)とプロパティ(longNameProperty、problematic)として正常にコード化しました。 longNamePropertyの問題は、コンストラクターと非常によく似たmorphメソッドのコードがあることです。この重複を排除する方法はありますか?

var Fruit = function (name) { 
    this.name = name; 

    this.longNameMethod = function() { 
     return this.name + this.name; 
    } 

    this.longNameProperty = this.name + this.name; 

    this.morph = function(name) { 
     this.name = name; 

     // starting to feel redundant 
     this.longNameProperty = this.name + this.name; 
    } 

    // update(); // hypothetical solution 
}; 

var item = new Fruit('apple'); 

console.log(item.longNameMethod()); // apple apple 
console.log(item.longNameProperty); // apple apple 

item.morph('orange'); 

console.log(item.longNameMethod()); // orange orange 
console.log(item.longNameProperty); // orange orange 

これらのプロパティのすべての更新を処理する「更新」メソッドを含めるようにしましたが、何らかの理由で構築中に使用できませんでした。 this.nameは未定義です。建設中の作業の順序はどうですか?

編集:メソッドのアプローチとプロパティのアプローチは機能的には外部と同じですが、目的はプロパティのアプローチを使用することです。

編集^ 2:だから私は複数の問題が遊びであると思います...ここで説明される1つのその:How does "this" keyword work within a function?

答えて

1

あなたはthisにそれを割り当てるときに、それを使用する前にメソッドを追加する必要があります。

var Fruit = function (name) { 
    this.morph = function(name) { 
     this.name = name; 

     this.longNameProperty = this.name + this.name; 
    } 

    this.morph(name); 
}; 

var item = new Fruit('apple'); 

console.log(item.longNameProperty); // apple apple 

item.morph('orange'); 

console.log(item.longNameProperty); // orange orange 
+0

シンプルなので、ありがとう!なぜこのような苦労があったのか分かりません... –

+0

ええ、私はそれを考えていました - シングルトンのようなものです – mplungjan

+0

あなたの提案は私の前にあるコードに直接マッピングされません、 できます。状態更新部分とmorphメソッドが2つの異なるメソッドであった場合、どうしてあなたは状態更新メソッドに引数を渡す必要がありますか? –

関連する問題