萬盛學電腦網

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

JavaScript 中 this 的四大綁定規則圖解

核心原則

this 永遠指向「呼叫該函式的物件」。判斷 this 指向,本質上是在判斷「函式屬於誰、被誰呼叫」。

四大規則

1. 物件方法呼叫 → 指向該物件

var obj = { value: 100, getValue: function() { console.log(this.value); } };
obj.getValue(); // 100,this = obj

2. 獨立函式呼叫 → 指向全域物件(瀏覽器為 window)

function foo() { console.log(this); }
foo(); // window
// 嚴格模式下為 undefined

常見坑:內部函式(閉包)的 this 也指向 window,非外層物件。解決用 var self = this、箭頭函式或 bind。

3. 建構函式(new) → 指向新建立的實例

function Person() { this.name = 'Tom'; }
var p = new Person(); // this = p
console.log(p.name); // Tom

new 內部做三件事:建立空物件、__proto__ 指向 prototype、呼叫建構函式並綁定 this。

4. call/apply/bind 顯式綁定 → 指向傳入的第一個參數

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(可再傳預設參數)

優先順序(由高到低)

  1. new 綁定
  2. 顯式綁定(call/apply/bind)
  3. 物件方法呼叫(隱式綁定)
  4. 預設綁定(全域/undefined)

箭頭函式特例

箭頭函式**沒有自己的 this**,捕獲定義時外層作用域的 this,call/apply/bind **無法改變**其 this 指向。

copyright © 萬盛學電腦網 all rights reserved