length 與索引存取。Array.prototype.slice.call(arguments) 可轉真陣列。[...arguments] 或 Array.from(arguments)。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,現代程式碼應避免使用。
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。