萬盛學電腦網

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

JavaScript 進階:caller、callee、call、apply 深度解析

arguments 隱含物件

  • 類陣列,擁有 length 與索引存取。
  • 非陣列:Array.prototype.slice.call(arguments) 可轉真陣列。
  • ES6:[...arguments] 或 Array.from(arguments)。

caller / callee

function foo() {
  console.log("caller:", foo.caller); // 呼叫 foo 的函式(嚴格模式下不可用)
  console.log("callee:", arguments.callee); // 正在執行的函式自身(嚴格模式禁用)
}
function bar() { foo(); }
bar(); // caller 指向 bar

// callee 用於匿名函式遞歸
var sum = function(n) {
  return n <= 1 ? 1 : n + arguments.callee(n - 1);
};

**注意**:ES5 嚴格模式("use strict")禁用 caller/callee,現代程式碼應避免使用。

call / apply:改變 this 指向

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}
var person = { name: "Alice" };

greet.call(person, "Hello", "!");        // 參數列表
greet.apply(person, ["Hi", "?"]);        // 參數陣列

// 應用:陣列最大值
Math.max.apply(null, [1, 5, 3]); // 5
// ES6 展開運算子更簡潔
Math.max(...[1, 5, 3]);

借用方法

// 類陣列借用陣列方法
var args = Array.prototype.slice.call(arguments);
var arrLike = { 0: "a", 1: "b", length: 2 };
Array.prototype.forEach.call(arrLike, function(v) { console.log(v); });

繼承模擬(經典寫法)

function Base() { this.member = "base"; }
Base.prototype.method = function() { console.log(this.member); };

function Derived() {
  Base.call(this); // 繼承實例屬性
  // Base.apply(this, arguments); // 帶參數版
}
Derived.prototype = Object.create(Base.prototype); // 原型鏈繼承
Derived.prototype.constructor = Derived;

var d = new Derived();
d.method(); // "base"

現代替代方案

  • 類別繼承:class Derived extends Base { ... }(ES6+)。
  • 函式綁定:fn.bind(thisArg, ...args) 回傳綁定後的新函式。
  • 箭頭函式自動捕捉外層 this,無需 call/apply。
copyright © 萬盛學電腦網 all rights reserved