簡體   English   中英

Javascript自定義對象需要偵聽另一個自定義對象事件

[英]Javascript custom object needs to listen to another custom objects event

我試圖讓一個自定義對象偵聽另一個自定義對象的事件。 我怎樣才能做到這一點? 我做了一個病人和護士的小例子。 當患者尖叫時,護士需要拿起電話並撥打911。

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難題?

最好的問候,雷米·薩穆爾斯基

我認為您在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

現在,我找到了解決方案。 您需要將Nurse上下文傳遞給患者的OnScream

試試這個:

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.');
    };
}    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM