プレゼンテーションシナリオ: スライド82
スライド82では、JavaScript this in Functionsについて説明します。
基本的な例
右側の図のコード例を見てください:
例1: Global scope
console.log(this);
// -> Window (browser), undefined (strict mode)
グローバルスコープでは、thisはWindowオブジェクト(ブラウザ内)を参照するか、undefined(strict mode)になります。
例2: Normal function
function testFunc() {
console.log(this);
}
testFunc();
// -> Window (non-strict), undefined (strict)
通常の関数では、thisもWindow(non-strict mode)またはundefined(strict mode)を参照します。
例3: Object method
const person = {
name: "Alice",
showName() { console.log(this.name); }
};
person.showName();
// -> "Alice"
オブジェクトメソッドでは、thisはそのメソッドを含むオブジェクトを参照します。ここでthis.nameはperson.name、つまり"Alice"を参照します。
例4: Event handler (browser only)
document.getElementById("btn").onclick = function() {
console.log(this); // -> <button>
};
イベントハンドラでは、thisはイベントをトリガーしたDOM要素を参照します。ここでは<button>タグです。
例5: call / bind
function greet() { console.log("Hi " + this.name); }
greet.call({ name: "Bob" }); // -> "Hi Bob"
call()またはbind()を使用して、thisを手動で割り当てます。ここではthisをオブジェクト{ name: "Bob" }に割り当てているため、this.nameは"Bob"になります。
以上で、関数内のthisについての説明を終わります。thisの値は、関数の呼び出し方と使用コンテキストに依存します。