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

猜你喜欢

转载自www.cnblogs.com/dreamsqin/p/12001092.html
今日推荐