萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深入淺出分析 JavaScript 中 this 的指向規則

核心結論

this 指向「函式執行時的當前物件」,簡單說:誰調用,this 就指向誰。

三大指向場景

1. 全域物件(window)

var msg = 'global';
function foo() { console.log(this.msg); }
foo(); // 'global',this = window

獨立函式呼叫,隸屬於 window,故 this === window。

2. 所屬物件(隱式綁定)


var obj = { msg: 'obj', foo: function() { console.log(this.msg); } };
obj.foo(); // 'obj',this = obj

透過 obj.foo() 呼叫,foo 的 this 綁定至 obj。

3. 建構函式(new 綁定)


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 至新物件。

顯式綁定:call / apply / bind


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,可預設參數(偏函式)

常見陷阱:回呼函式丟失 this


var obj = { val: 1, foo: function() { setTimeout(function() { console.log(this.val); }, 100); } };
obj.foo(); // undefined(setTimeout 回呼 this = window)

解決方案

  1. var self = this; setTimeout(function() { console.log(self.val); }, 100);
  2. setTimeout(() => console.log(this.val), 100);(箭頭函式捕獲外層 this)
  3. setTimeout(function() { console.log(this.val); }.bind(this), 100);

優先順序總表

優先序規則範例
1new 綁定new Fn()
2顯式綁定fn.call(obj), fn.bind(obj)
3隱式綁定obj.fn()
4預設綁定fn() → window/undefined

箭頭函式無 this,不參與上述規則,永遠捕獲定義時的外層 this。

copyright © 萬盛學電腦網 all rights reserved