Arguments 對象、call()與apply()

Arguments 對象

arguments:是一個對應於傳遞給函數的參數的類數組對象。arguments對象是所有(非箭頭)函數中都可用的局部變量,你可以使用arguments對象在函數中引用函數的參數。此對象包含傳遞給函數的每個參數,第一個參數在索引0處。

ps:arguments對象不是一個 Array ,它類似於Array,但除了length屬性和索引元素之外沒有任何Array屬性和方法。但可以被轉換爲一個真正的Array,方式如下:

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);
const args = [...arguments];

參考資料:

1、arguments:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments


call()與apply()——用於改變this指向

call():使用一個指定的 this 值和單獨給出的一個或多個參數來調用一個函數,接受的是一個參數列表

let obj1 = {
    a: '我是obj1的a',
    fn: function(msg) {
        console.log(msg + this.a);
    }
}

let obj2 = {
    a: '我是obj2的a'
}

// 正常調用
obj1.fn('你說啥?')    // 你說啥?我是obj1的a

// call()調用
obj1.fn.call(obj2, '你說啥?')    // 你說啥?我是obj2的a


apply():使用一個指定的 this 值和單獨給出的一個數組(['eat', 'bananas'])或數組對象(new Array('eat', 'bananas'))參數來調用一個函數,接受的是一個包含多個參數的數組

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);   // apply巧用,將數組轉換爲參數列表,等同於`Math.max(...numbers)`

console.log(max);   // expected output: 7

const min = Math.min.apply(null, numbers);

console.log(min);   // expected output: 2

apply巧用:將具有length屬性的對象轉成數組[].slice.call(arguments)

參考資料:

1、call():https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
2、apply():https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
3、展開語法:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章