DIV CSS 佈局教程網

JavaScript call() 方法詳解:用法、參數與實戰示例
編輯:JavaScript綜合知識     

call() 是 JS 面試的高頻考點,也是理解 this 綁定機制的最佳入口。Mozilla 官方對它的定義是:在使用一個指定的 this 值和若干指定的參數值的前提下調用某個函數或方法。

語法與參數

fun.call(thisArg[, arg1[, arg2[, ...]]])

thisArg:在 fun 運行時指定的 this 值。注意一個容易忽略的細節——指定的 this 並不一定是函數執行時真正的 this。如果函數處於非嚴格模式,傳入 null 或 undefined 會被自動替換為全局對象(瀏覽器裡就是 window);傳入原始值(數字、字符串、布爾值)時,this 會指向該值的包裝對象。

arg1, arg2, ...:傳給目標函數的參數列表,這也是 call 與 apply 的唯一區別——前者逐一列出,後者接收數組。

從最簡單的例子開始

function print(p1, p2) {
  console.log(p1 + ' ' + p2);
}
print("Hello", "World");
print.call(undefined, "Hello", "World");

兩種寫法輸出相同,但 call 多傳了一個 undefined,此時它確實沒有發揮作用。換個例子:

function print(name) {
  console.log(this.p1 + ' ' + this.p2);
}

var h = {p1:"hello", p2:"world", print:print};
h.print("fd");

var h2 = {p1:"hello", p2:"world"};
print.call(h2, "nothing");

這裡就看出價值了:h2 本身並沒有 print 方法,但通過 call 我們讓它「借用」了 print 的行為,函數內部的 this 指向 h2。這就是 call 的核心用途——借用別人的方法。

經典場景:實現繼承

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0)
    throw RangeError('Cannot create product "' + name + '" with a negative price');
  return this;
}

function Food(name, price) {
  Product.call(this, name, price);   // 關鍵一行
  this.category = 'food';
}
Food.prototype = new Product();

var cheese = new Food('feta', 5);
console.log(cheese);

用 Food 構造函數創建的實例,會擁有 Product 裡添加的 name 與 price 屬性,而 category 在各自構造函數中定義。這就是「構造函數繼承」的經典寫法,本質是把子類實例的 this 傳給父類構造函數執行一遍。

也可以直接在函數內部調用:

var h2 = function(no){
  this.p1 = "hello";
  this.p2 = "world";
  print.call(this, "nothing");
};
h2();

call 的三個主要優勢

1. 可以自定義接收者來調用函數;
2. 可以調用在指定對象上並不存在的方法(方法借用,比如用 Array.prototype.slice.call(arguments) 把類數組轉真數組);
3. 可以定義高階函數,允許調用者為回調函數指定接收者。

理解 call 的關鍵是記住:它改變的是函數執行時的 this 指向,函數本身的定義完全沒動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved