萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

JavaScript 函數呼叫模式與方法呼叫模式中 this 綁定差異示例

注意:原文代碼為 JavaScript 而非 PHP。此處保留原標題但修正說明,釐清 JS 中 this 綁定規則。

代碼場景

var doubling = function(x) { return x * 2; };

var obj = {
  val: 100,
  prop: (function() {
    var that = this;
    console.log('name: ' + that + '; type: ' + typeof that); // [object Window], object
    return doubling(that.val); // this 是 window,val 不存在 → NaN
  })(),
  get_prop: function() {
    var that = this;
    console.log('name: ' + that + '; type: ' + typeof that); // [object Object], object
    return doubling(that.val); // this 是 obj,val=100 → 200
  }
};

執行結果分析

屬性/方法初始化/呼叫時機this 指向結果
prop (IIFE)物件字面量定義階段立即執行全域物件 window (非嚴格模式)NaN
get_prop()後續手動呼叫 obj.get_prop()物件 obj200

核心規則

  1. 函數呼叫模式: func() → this 綁定全域物件 (瀏覽器為 window),嚴格模式為 undefined。
  2. 方法呼叫模式: obj.method() → this 綁定 obj。
  3. 建構器模式: new Func() → this 綁定新建實例。
  4. apply/call/bind: 顯式指定 this。

常見坑與修正

// 坑:回調函數丟失 this
obj.callback = function() { console.log(this.val); };
setTimeout(obj.callback, 100); // this 變 window

// 修正 1: 箭頭函數 (詞法綁定)
setTimeout(() => obj.callback(), 100);

// 修正 2: bind
setTimeout(obj.callback.bind(obj), 100);

// 修正 3: 變數緩存 (舊寫法)
var that = this;
setTimeout(function() { console.log(that.val); }, 100);

PHP 差異提示

PHP 中 $this 在類方法內永遠指向當前實例,不存在「丟失 this」問題。PHP 5.4+ 支援 Closure::bind / bindTo 手動綁定閉包 $this,但極少直接用於業務代碼。

copyright © 萬盛學電腦網 all rights reserved