DIV CSS 佈局教程網

JavaScript call 與 apply 的差異及繼承、回呼實戰
編輯:JavaScript基礎知識     

一、方法定義

call 方法

語法:fun.call(thisArg[, arg1[, arg2[, ...]]])

定義:呼叫某物件的方法,並以另一個物件取代當前物件作為 this。

說明:call 可以把函式的物件上下文從原本的環境,切換成由 thisArg 指定的新物件。若未提供 thisArg,則以 Global 物件作為 thisArg。

apply 方法

語法:fun.apply(thisArg[, argsArray])

定義:套用某物件的方法,並以另一個物件取代當前物件。

說明:如果 argArray 不是有效陣列也不是 arguments 物件,會丟出 TypeError。若 argArray 與 thisArg 都未提供,則 Global 物件作為 thisArg,且無法傳入任何參數。

二、兩者的核心差異

差別只在「怎麼傳參數」:call 把參數逐一列舉,apply 則接收一個陣列或 arguments 物件。

2.1 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();

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}
Toy.prototype = new Product();

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

2.2 apply 版本

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.apply(this, arguments);
  this.category = 'food';
}
Food.prototype = new Product();

function Toy(name, price) {
  Product.apply(this, arguments);
  this.category = 'toy';
}
Toy.prototype = new Product();

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

apply 搭配 arguments 的好處很明顯:參數清單不必重抄一遍,父類建構子增減參數時子類完全不用改。

三、實戰場景

3.1 模擬類別繼承

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.alertName = function () { alert(this.name); };
  this.alertAge  = function () { alert(this.age);  };
}

function webDever(name, age, sex) {
  Person.call(this, name, age);
  this.sex = sex;
  this.alertSex = function () { alert(this.sex); };
}

var test = new webDever("設計蜂巢", 24, "男");
test.alertName(); // 設計蜂巢
test.alertAge();  // 24
test.alertSex();  // 男

3.2 回呼函式中保住 this

function Album(id, title, owner_id) {
  this.id = id;
  this.name = title;
  this.owner_id = owner_id;
}

Album.prototype.get_owner = function (callback) {
  var self = this;
  $.get('/owners/' + this.owner_id, function (data) {
    callback && callback.call(self, data.name);
  });
};

var album = new Album(1, '設計蜂巢', 2);
album.get_owner(function (owner) {
  alert('The album ' + this.name + ' belongs to ' + owner);
});

這裡的關鍵是:Ajax 回呼裡的 this 已經不是 album 了,所以用 call 把上下文重新綁回 self,回呼內部才能正確讀到 this.name。

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