說明:###
- call() 方法在使用一個指定的this值和若干個指定的參數值的前提下調用某個函數或方法.
語法:###
*fun*.call(*thisArg*[, *arg1*[, *arg2*[, ...]]])
參數:###
thisArg
在fun函數運行時指定的this值。需要注意的是,指定的this值并不一定是該函數執行時真正的this值,如果這個函數處于非嚴格模式下,則指定為null和undefined的this值會自動指向全局對象(瀏覽器中就是window對象),同時值為原始值(數字,字符串,布爾值)的this會指向該原始值的自動包裝對象。
arg1, arg2, ...
指定的參數列表。
- apply()方法和call()功能一樣,區別在于參數不一樣,apply方法只接受一個數組參數
語法:###
fun.apply(thisArg[, argsArray])
參數:###
thisArg
在 fun 函數運行時指定的 this 值。需要注意的是,指定的 this 值并不一定是該函數執行時真正的 this 值,如果這個函數處于非嚴格模式下,則指定為 null 或 undefined 時會自動指向全局對象(瀏覽器中就是window對象),同時值為原始值(數字,字符串,布爾值)的 this 會指向該原始值的自動包裝對象。
argsArray
一個數組或者類數組對象,其中的數組元素將作為單獨的參數傳給 fun 函數。如果該參數的值為null 或 undefined,則表示不需要傳入任何參數。從ECMAScript 5 開始可以使用類數組對象。瀏覽器兼容性請參閱本文底部內容
舉例:###
var animals =
{species: 'Lion', name: 'King'}
function greet() {
var reply = [this.species, 'Is An Awesome', this.name].join(' ');
console.log(reply);
}
greet.call(animals)
greet.apply(animals)
輸出效果:###
Paste_Image.png
理解:###
//上面的代碼等同于
var animals = {
species: 'Lion',
name :'King',
}
animals.greety = function () {
var reply = [this.species, 'Is An Awesome', this.name].join(' ');
console.log(reply);
}
animals.greety()
可以按java的繼承概念理解:animal對象繼承了greet對象的屬性和方法,那么animal對象則可以擁有greety對象方法
另一個例子:###
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}
}
//在Food中調用了Pruduct的構造函數,更加形象的說明了繼承關系
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
//等同于
function Food(name, price) {
this.name = name;
this.price = price;
if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}
this.category = 'food';
}