萬盛學電腦網

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

JavaScript call 與 apply 深度解析:參數差異、上下文綁定與繼承實戰

call 與 apply 是 Function 原型上的核心方法,作用相同——指定 this 上下文調用函數,唯一區別在參數傳遞方式。

語法對比

func.call(thisArg, arg1, arg2, ...); // 參數列表
func.apply(thisArg, [argsArray]);    // 參數數組(或類數組)

核心用例 1:借用方法計算矩形面積

function Rectangle(len, width) {
  this.len = len;
  this.width = width;
}

function multiply(a, b) {
  return a * b;
}

const rect = new Rectangle(15, 30);

// call: 參數逐個傳遞
const area1 = multiply.call(rect, rect.len, rect.width);

// apply: 參數打包為數組
const area2 = multiply.apply(rect, [rect.len, rect.width]);

console.log(area1, area2); // 450 450

核心用例 2:實現類式繼承(經典模式)

// 父構造函數
function Person(name) {
  this.name = name;
  this.sayHello = function() { return `hello, ${this.name}`; };
}

// 子構造函數
function Student(name, sex, school) {
  // 關鍵:借用父構造函數初始化 this
  Person.call(this, name);
  
  // 子類自身屬性
  this.sex = sex;
  this.school = school;
}

const stu = new Student('fengjx', '男', '廣西機電職業技術學院');
console.log(stu.sayHello()); // "hello, fengjx"
console.log(stu.sex, stu.school); // 男 廣西機電職業技術學院

原理:Person.call(this, name) 在子構造函數執行上下文中執行父構造函數,將 this.name、this.sayHello 掛載到子實例上。

進階:借用數組方法處理類數組對象

// arguments 轉真數組
const args = Array.prototype.slice.call(arguments);
// 或 ES6
const args = [...arguments];

// 遍歷 NodeList
Array.prototype.forEach.call(document.querySelectorAll('div'), el => {
  el.style.color = 'red';
});

// Math.max 求數組最大值
Math.max.apply(null, [1, 5, 3]); // 5
// ES6 展開運算符更簡潔
Math.max(...[1, 5, 3]);

call/apply vs bind

方法執行時機返回值典型用途
call立即執行函數執行結果動態上下文調用、繼承
apply立即執行函數執行結果數組參數、數學運算
bind返回新函數綁定後的函數事件處理、柯里化、延遲綁定

性能提示

  • 現代引擎優化極好,日常開發性能差異可忽略。
  • 高頻調用熱點路徑可考慮箭頭函數捕獲 this 或預綁定 bind。

總結

call 分散參數,apply 聚合數組,本質都是顯式綁定 this。掌握它們是理解 JS 函數調用機制、實現繼承、借用原生方法的關鍵。ES6+ 箭頭函數、展開運算符、Reflect.apply 提供了更現代的替代選擇,但理解底層原理仍不可或缺。

copyright © 萬盛學電腦網 all rights reserved