我正在尝试让自定义对象侦听另一个自定义对象的事件。我怎样才能做到这一点?我做了一个病人和一名护士的小例子。当病人尖叫时,护士需要拿起电话拨打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.');
但此与发件人相同,并输出:“John听到John尖叫。”这很好,但我想简听到约翰的尖叫声。我该如何解决这个JavaScript难题?
祝你好运, 雷米·萨穆尔斯基
答案 0 :(得分: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 强>
现在我找到了解决方案。您需要将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.');
};
}