this
part1からのつづき。
GoogleConsoleのデバッグコンソールで以下を実行してみる。
const Person = function (name) { this.name = name; return this; };
Person('somebody'); //Window {0: Window, window: Window, self: Window, document: document, name: 'somebody', location: Location, …}
グローバルオブジェクトのnameプロパティをsomebodyに変更してしまった!
strictモードだと、
const Person = function (name) { 'use strict'; this.name = name; return this; };
Person('somebody'); //Uncaught TypeError: Cannot set properties of undefined (setting 'name')
at Person (<anonymous>:1:58)
at <anonymous>:2:1
thisにundefinedが入り、グローバルオブジェクトは変更できなくなっている。
よって、クラス構文内はstrictモードで実行されるため、thisにundefinedが入る場合がある。
class Person {
constructor(name) {
this.name = name;
}
greet() {
const doIt = function () {
console.log(`こんにちは、 ${this.name}です。`);
};
doIt();
}
}
const aichan = new Person('Aichan');
aichan.greet(); // TypeError: Cannot read property 'name' of undefined
doItのthisはundefinedになってしまう。
この場合どうしたらよいか?
アロー関数式を推奨
class Person {
constructor(name) {
this.name = name;
}
greet = () => {
const doIt = () => {
console.log(`こんにちは、 ${this.name}です。`);
};
doIt();
}
}
const aichan = new Person('Aichan');
aichan.greet(); // こんにちは、 Aichanです。
アロー関数は暗黙の引数としての
this を持たず、this を参照すると関数の外のスコープの this の値がそのまま使われる
よって、
・thisはクラス構文内だけで使うようにする。
・クラス構文内のメソッドは、アロー関数式で定義する。
というルールが良い。
0 件のコメント:
コメントを投稿