JavaScript中的call、apply
JavaScript中的call、applycall
JavaScript中的call是調用一個函數,在調用函數時,將this的值綁定為call參數中的第一個參數。
var bye = function(param, param2){ console.log(this); console.log(param); console.log(param2); console.log("bye"); console.log(this.x)}t = {'x': 1};bye.call(t, 1, 2);
其結果為:
Object {x: 1}
1
2
bye
1
當然,我們也可以將this值綁定為一個原始值,調用上述函數:
bye.call(5, 1, 2);
其結果為:
Number {[[PrimitiveValue]]: 5}
1
2
bye
在non-strict 模式下,如果我們將null,undefined和原始類型的值傳給this參數,其this值將被global代替,在MDN中有這樣的說明:
thisArg
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
call函數的作用就是我們在調用方法時可以設定一個不同的對象,因為其預設的對象就是當前對象,正因為這樣,我們可以唯寫一次該方法,在另一對象中繼承該方法,然後調用它,而不需要再寫一遍該方法。MDN中對該方法的介紹:
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
應用情境一:利用call實現繼承(Using call to chain constructors for an object)
function Product(name, price) { this.name = name; this.price = price; if (price < 0) { throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } return this;}function Food(name, price) { Product.call(this, name, price); this.category = 'food';}Food.prototype = Object.create(Product.prototype);function Toy(name, price) { Product.call(this, name, price); this.category = 'toy';}Toy.prototype = Object.create(Product.prototype);var cheese = new Food('feta', 5);var fun = new Toy('robot', 40);
Food和Toy利用call繼承了Product的name和price,然後各自又有了category 屬性。
應用情境二:利用call調用匿名函數(Using call to invoke an anonymous function)
var animals = [ { species: 'Lion', name: 'King' }, { species: 'Whale', name: 'Fail' }];for (var i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i);}
apply
apply與call幾乎完全相同,只是在傳遞參數時apply傳遞的是數組(array)或者是類似數組的對象( array-like object),其調用方式:
fun.apply(this, ['eat', 'bananas']);fun.apply(this, new Array('eat', 'bananas'));