taquaki-satwo
11/29/2017 - 2:47 AM

イベントリスナのthis

JS-イベントリスナのthis

function Person(name) {
  this.name = name;
}
Person.prototype.sayHello = function() {
  console.log(`Hello ${this.name}`);
}

const person = new Person('Tom');
const button = document.getElementById('button');

button.addEventListener('click', person.sayHello, false); // -> "Hello "

// thisを指定したオブジェクトに設定する

// bindを使う
button.addEventListener('click', person.sayHello.bind(person), false); // -> "Hello Tom"

// 無名関数を使う
button.addEventListener('click', function(e) {
  person.sayHello();
}, false);

// アロー関数を使う
// prototypeにアロー関数を定義するとthisはwindowオブジェクトになるのでコンストラクタに書く
// function Person(name) {
//   this.name = name;
//   this.sayHello = () => {
//     console.log(`Hello ${this.name}`);
//   };
// }

// handleEventメソッドを使う
Person.prototype.handleEvent = function() {
  console.log(`HandleEvent ${this.name}`);
}
const person2 = new Person('Bob');
button.addEventListener('click', person2, false);

JS-イベントリスナのthis

A Pen by Takaaki Sato on CodePen.

License.

input#button(type='button' value='button')