萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

深度解析 JavaScript this 綁定:四大調用模式與陷阱避坑

核心認知:this 是什麼?

  • this 是執行上下文的屬性,而非變量對象屬性
  • 不參與標識符解析,無作用域鏈查找,進入上下文時一次性確定
  • 任何對象均可作為 this 值

四大調用模式決定 this 指向

1. 方法調用模式

函數作為對象屬性被調用,this 綁定到該對象。

const obj = {
  value: 0,
  increment(n) { this.value += n || 1; }
};
obj.increment();      // this → obj
obj.increment(2);     // this → obj

2. 函數調用模式

函數獨立調用(非對象屬性),this 綁定到全局對象(瀏覽器中為 window)。設計缺陷:內部函數無法直接訪問外部 this。

function foo() { console.log(this); }
foo();  // window

// 經典修復:捕獲外部 this
const obj = {
  value: 1,
  double() {
    const that = this;          // 捕獲
    function helper() {
      that.value *= 2;          // 訪問 that
    }
    helper();
  }
};

3. 構造器調用模式

使用 new 調用函數,創建新對象並綁定 this 到新實例。原型方法中的 this 指向調用實例,而非原型對象。

function Quo(status) {
  this.status = status;   // this → 新實例
}
Quo.prototype.getStatus = function() {
  return this.status;     // this → 調用 getStatus 的實例
};
const q = new Quo('confused');
q.getStatus(); // 'confused'

4. Apply/Call/Bind 調用模式

顯式指定 this 值:

func.apply(thisArg, [argsArray]);
func.call(thisArg, arg1, arg2...);
const bound = func.bind(thisArg);

核心:劫持/借用其他對象的方法,實現繼承或上下文切換。

經典面試題解析

var test = function() {};
test.prototype = {
  foo: "apple",
  fun: function() { this.foo = "banana"; }
};
var myTest = new test();
myTest.fun();
console.log(myTest.hasOwnProperty("foo")); // true
console.log(myTest.hasOwnProperty("fun")); // false

解析:

  1. myTest.fun() 為方法調用,this 指向 myTest
  2. this.foo = "banana" 在實例上創建自有屬性 foo,覆蓋原型鏈同名屬性
  3. hasOwnProperty("foo") → true(實例自有)
  4. fun 定義在原型上,實例無自有 fun → false

現代最佳實踐

  • 箭頭函數:無自身 this,詞法作用域捕獲外層 this,完美解決回調嵌套問題
  • 類語法:class 內方法默認非綁定,實例調用時自動綁定
  • 事件處理器:用 handler.bind(this) 或箭頭函數屬性 handleClick = () => {}
copyright © 萬盛學電腦網 all rights reserved