2017-03-02 2 views
0

私はカスタムオブジェクトを別のカスタムオブジェクトのイベントをリッスンさせようとしています。これどうやってするの?私は患者と看護師の小さな例を作りました。患者が悲鳴ときに看護師が電話をピックアップする必要があり、これは動作しますが、今、私のような警告の内側に看護師の名前を持つようにしたい911Javascriptカスタムオブジェクトは、別のカスタムオブジェクトイベントをリッスンする必要があります

function Patient(name) { 
    this.Name = name; 

    this.Scream = function (terribleSound) { 
     alert(terribleSound); 
     if (typeof this.OnScream === "function") { 
      setTimeout(this.OnScream(this), 1); 
     } 
    } 
} 

function Nurse(name, patient) { 
    this.Name = name; 
    this.Patient = patient; 

    this.Patient.OnScream = function (sender) { 
     alert(sender.Name + ' screamed'); 
    } 
} 

var patient = new Patient('John'); 
var nurse = new Nurse('Jane', patient); 
patient.Scream('AAAAAAAHHHHHHHHhhhhhh!'); 

を呼び出す:

alert(this.Name + ' heard ' + sender.Name + ' scream.'); 

しかしこのセンダと同じで、「ジョンはジョンの叫び声を聞いた」と出力します。それはかなりうまいですが、ジェーンがジョンの叫び声を聞きたかったのです。このJavaScriptパズルをどのように解決できますか?

敬具、 レミーSamulski

答えて

1

私はあなたがScream機能でタイムアウトを必要とは思いません。しかし、あなたがしなければ、これを見て:

this.Scream = function (terribleSound) { 
    alert(terribleSound); 
    if (typeof this.OnScream === "function") { 
     setTimeout(function(){this.OnScream(this)}.bind(this), 1); 
    } 
} 

あなたがタイムアウトを必要としない場合:

this.Scream = function (terribleSound) { 
    alert(terribleSound); 
    if (typeof this.OnScream === "function") { 
     this.OnScream(this); 
    } 
} 

UPD

を今、私は解決策を発見しました。患者のOnScreamNurseのコンテキストを渡す必要があります。

は、この方法を試してください。

function Nurse(name, patient) { 
    this.Name = name; 
    this.Patient = patient; 

    this.Patient.OnScream = function (sender) { 
     alert(this.Name + ' heard ' + sender.Name + ' scream.'); 
    }.bind(this); 
} 

または閉鎖して:あなたの提案を

function Nurse(name, patient) { 
    var self = this; 
    this.Name = name; 
    this.Patient = patient; 

    this.Patient.OnScream = function (sender) { 
     alert(self.Name + ' heard ' + sender.Name + ' scream.'); 
    }; 
}  
+0

Thxをします。両方の例を試したが、依然としてジョンだけが叫んで聞こえ、ジェーンはまだジョンの叫び声を聞いていない。タイムアウトを使用してthis.Scream関数が終了するまで待っていましたが、ジェーンのonScream反応の前に終了しました。タイムアウトを使用しない場合、実際のthis.Screamを終了する前に「イベント」が既にトリガーされています。 –

+0

@ LiQuick.netの回答 – MysterX

+0

ありがとう、両方のソリューションが動作します。この_bind()_関数が何をしているかを見ていきます。 THX! –

関連する問題