this 永遠指向「呼叫該函式的物件」。判斷 this 指向,本質上是在判斷「函式屬於誰、被誰呼叫」。
var obj = { value: 100, getValue: function() { console.log(this.value); } };
obj.getValue(); // 100,this = obj
function foo() { console.log(this); }
foo(); // window
// 嚴格模式下為 undefined
常見坑:內部函式(閉包)的 this 也指向 window,非外層物件。解決用 var self = this、箭頭函式或 bind。
function Person() { this.name = 'Tom'; }
var p = new Person(); // this = p
console.log(p.name); // Tom
new 內部做三件事:建立空物件、__proto__ 指向 prototype、呼叫建構函式並綁定 this。
function greet() { console.log(this.name); }
var a = { name: 'A' }, b = { name: 'B' };
greet.call(a); // A
greet.apply(b); // B
var bound = greet.bind(a); bound(); // A
call:參數逐個傳遞 fn.call(obj, a, b)apply:參數以陣列傳遞 fn.apply(obj, [a, b])bind:回傳新函式,永久綁定 this(可再傳預設參數)new 綁定箭頭函式**沒有自己的 this**,捕獲定義時外層作用域的 this,call/apply/bind **無法改變**其 this 指向。