在事件回调中将事件对象传递给 setter 方法

Pass event object to setter method in event callback

我正在使用 createjs 库。

我有以下 class:

class Person {
 constructor(){
  this.name = 'John';
 }

 set updateName(event){
  this.name += event.key;
 }
}

接下来,我像这样实例化对象:

var human = new Person();

我正在尝试在每次击键时更新此人的姓名,如下所示:

window.addEventListener.on('keydown', human.updateName);

但是,我收到 "Cannot read property 'handleEvent' of undefined" 的错误。

human.updateName 尝试读取 updateName 属性。由于您尚未为其定义 getter,因此其结果为 undefined。显然,无论您将其传递给 (window.addEventListener.on),都希望传递给 undefined.

以外的其他内容

要传递实际的 setter 函数有点棘手,您必须通过 getOwnPropertyDescriptor 访问它,然后将其传递给:

window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set);

为了确保正确的人得到更新,您可能还需要bind

window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set.bind(human));

或者,使用箭头函数作为胶水会更简单:

window.addEventListener.on('keydown', e => {
    human.updateName = e;
});

旁注:updateName 是您给 方法 而不是 属性 的那种名称。通常,属性 会简单地称为 name.

也许您打算将其改为一种方法?如果是:

class Person {
 constructor(){
  this.name = 'John';
 }

 updateName(event){ // No `set` on this line
  this.name += event.key;
 }
}

...和

window.addEventListener.on('keydown', human.updateName.bind(human));

window.addEventListener.on('keydown', e => {
    human.updateName(e);
});