萬盛學電腦網

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

JavaScript call() 方法深度解析:改變 this 指向與函數借用

Function.prototype.call() 允許在指定 this 上下文中調用函數,並接受參數列表。是實現繼承、借用方法、顯式綁定上下文的核心工具。

語法與參數

func.call(thisArg, arg1, arg2, ...)
  • thisArg:函數執行時的 this 值。非嚴格模式下 null/undefined 指向全局對象 (window),原始值會被包裝為對象。
  • arg1, arg2...:傳遞給函數的參數列表(與 apply 的數組參數不同)。

核心用法示例

1. 基本調用 (等同直接調用)

function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}
var obj = { name: 'Alice' };
greet.call(obj, 'Hello', '!'); // "Hello, Alice!"

2. 借用其他對象的方法

var obj1 = { name: 'A', say: function() { console.log(this.name); } };
var obj2 = { name: 'B' };
obj1.say.call(obj2); // "B" - obj2 借用 obj1.say

3. 構造函數繼承 (經典模式)

function Product(name, price) {
  this.name = name;
  this.price = price;
  if (price < 0) throw RangeError('價格不能為負');
}

function Food(name, price) {
  Product.call(this, name, price); // 繼承 Product 屬性
  this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food;

var cheese = new Food('feta', 5);
console.log(cheese.name, cheese.price, cheese.category); // feta 5 food

4. 類數組轉真數組

function toArray(args) {
  return Array.prototype.slice.call(arguments);
  // 或 ES6: return [...arguments];
}
console.log(toArray(1,2,3)); // [1,2,3]

5. 綁定回調上下文 (事件處理常見)

var handler = {
  message: 'Event fired',
  handleClick: function() { console.log(this.message); }
};
// 錯誤:btn.onclick = handler.handleClick; // this 指向 btn
// 正確:
btn.onclick = handler.handleClick.bind(handler);
// 或舊式:
btn.onclick = function() { handler.handleClick.call(handler); };

call vs apply vs bind

方法參數形式返回值執行時機
call列表函數返回值立即執行
apply數組/類數組函數返回值立即執行
bind列表新函數 (綁定 this)稍後調用

嚴格模式差異

'use strict';
function f() { return this; }
f.call(null);   // null (非嚴格模式下為 window)
f.call(undefined); // undefined
f.call(7);      // Number {7} (原始值被包裝)
copyright © 萬盛學電腦網 all rights reserved