本文围绕以下问题进行分析:
arguments是什么?
arguments的作用?
arguments的地位和发展趋势。
arguments是什么?
先看一段代码
function test() {
console.log(arguments);
console.log(typeof arguments);
}
test(1, 2, 3, 4)
console.log(test.arguments);
分析控制台的输出
-
arguments的表现形式不完全符合数组或者对象,既有数组的下标和length属性,又有对象的属性和方法,最重要的是[[prototype]]继承的不是数组的方法,而是对象的方法。
-
像这样拥有下标和length属性,却不继承数组原型方法的对象,我们称之为类数组
-
因此,arguments是一个按顺序储存了函数实际入参的类数组对象。
arguments的作用?
1- arguments是实参列表,通过arguments可以知道和获取函数所传入的实参。
2- callee方法,通过arguments.callee可以找到当前函数本身。
//案例1
function test() {
console.log(arguments.callee);
}
test(1, 2, 3, 4)
//案例2
(function () {
console.log(arguments.callee)
}(1,2,3));
3- 我们再来看看arguments和形参的关系。
//案例1 修改形参值
function test(a, b) {
a = 30;
console.log('a-b', a, b);
console.log("arguments", arguments)
}
test(10, 20);
//案例1 修改arguments的值
function test(a, b) {
arguments[0] = 30;
console.log('a-b', a, b);
console.log("arguments", arguments)
}
test(10, 20);
// 案例3 给形参加上默认值 再修改形参
function test(a, b = 1) {
a = 30;
console.log('a-b', a, b);
console.log("arguments", arguments)
}
test(10, 20);
// 案例4
function test(a, b = 1) {
arguments[0] = 30;
console.log('a-b', a, b);
console.log("arguments", arguments)
}
test(10, 20);
分析以上4个案例
- 当函数形参没有默认值时,修改形参,相应的arguments会有发生改变,同样的,修改argument,相应的形参也会发生改变
- 当函数有默认值时,单独修改形参或者arguments,并不会导致另外一个值做出相应的更改。
arguments的地位和发展趋势。
通过以上的分析,我们知道了arguments最主要的两个作用
1-获取实参列表
2-通过arguments.callee访问函数本身
那我们是否可以通过其他途径,来实现这两个功能呢
请看以下代码
function test(...arg) {
console.log('arg', arg);
console.log('typeof arg', typeof arg);
console.log('toString.call(arg)', toString.call(arg));
console.log('test', test);
}
test(1, 2, 3, 4);
获取实参列表和访问函数本身的功能我们都可通过其他方式实现,并且获取到的实参列表还是数组的类型,更方便了对其接下来的操作,这么看的话,arguments的作用趋势是否已经开始渐渐的被弱化了呢?这有待大家去思考和探究了