this 指向「函式執行時的當前物件」,簡單說:誰調用,this 就指向誰。
var msg = 'global';
function foo() { console.log(this.msg); }
foo(); // 'global',this = window
獨立函式呼叫,隸屬於 window,故 this === window。
var obj = { msg: 'obj', foo: function() { console.log(this.msg); } };
obj.foo(); // 'obj',this = obj
透過 obj.foo() 呼叫,foo 的 this 綁定至 obj。
function Person() { this.age = 1; this.name = 'noname'; }
var p = new Person(); // this = 新建立的 p 實例
console.log(p.age, p.name); // 1, 'noname'
new 內部執行 Person.call(p),以 call 強制綁定 this 至新物件。
var obj = { val: 100 };
function bar() { console.log(this.val); }
bar.call(obj); // 100
bar.apply(obj); // 100
var bound = bar.bind(obj); bound(); // 100
call:參數逐個列舉 fn.call(ctx, a, b)apply:參數以陣列傳遞 fn.apply(ctx, [a,b])bind:回傳新函式,永久綁定 this,可預設參數(偏函式)
var obj = { val: 1, foo: function() { setTimeout(function() { console.log(this.val); }, 100); } };
obj.foo(); // undefined(setTimeout 回呼 this = window)
var self = this; setTimeout(function() { console.log(self.val); }, 100);setTimeout(() => console.log(this.val), 100);(箭頭函式捕獲外層 this)setTimeout(function() { console.log(this.val); }.bind(this), 100);| 優先序 | 規則 | 範例 |
|---|---|---|
| 1 | new 綁定 | new Fn() |
| 2 | 顯式綁定 | fn.call(obj), fn.bind(obj) |
| 3 | 隱式綁定 | obj.fn() |
| 4 | 預設綁定 | fn() → window/undefined |
箭頭函式無 this,不參與上述規則,永遠捕獲定義時的外層 this。