Function.prototype.apply()
apply()方法使用一個指定的this值和一個數(shù)組來調(diào)用一個函數(shù)。
function.apply(thisArg,[argsArray])
thisArg
這個是必選的,在function運行的時候使用該 this 值,但是 this可能不是該方法看的實際值。在非嚴格模式下就算使用function.apply()
括號里面不加任何東西凰荚,他也會指向全局對象。因為 this 為 null 或者 undefined 時會自動替換為指向全局對象,原始值會被包裝寡喝。
argsArray
這個是可選的,它是一個數(shù)組或者累數(shù)組對象勒奇,他作為一個單獨的參數(shù)傳給 function 函數(shù)预鬓。如果該參數(shù)的值為null或者 undefined 時則表示不傳任何參數(shù)。另外赊颠,該參數(shù)里面還可以使用數(shù)組字面量例如 function.apply(this,['name','age'])
格二,或者使用數(shù)組對象例如function.apply(this, new Array('name','age'))
。
apply用法示例
var array1 = [1,2,3,4,5];
function max(){
let n= this[0] ;
for( i = 0; i < this.length; i++){
if (n < this[i]){
n = this[i];
}}
return console.log(n);
}
max.apply(array1);//output 5
通過apply的方式傳入指定的this給求最大值的函數(shù)max并求出傳入數(shù)組中最大的那個值竣蹦。