理解函数调用-arguments参数
1.函数中两个隐含的参数:arguments和this
2.调用函数的不同方式
3.处理函数上下文的问题
隐式的函数参数this和arguments。两者会被静默地传递给参数,并且可以像函数体内显示声明的参数一样被正常访问。
参数this表示被调用函数的上下文对象,而argument参数表示函数调用过程中传递的所有参数。
这两个参数在JavaScript代码中至关重要。参数this是JavaScript面向对象编程的基本要素之一,通过arguments参数我们可以访问函数过程中传递的实际参数。正因为如此,接下来会探讨这些隐式参数的常见误区。
JavaScript中函数调用方式有多种。调用函数的方式对函数的隐式参数由很大的影响。
问题:
1.为什么this参数表示函数上下文?
2.函数(function)和方法(method)之间有什么区别?
3.如果一个构造函数显示返回一个对象会发生什么?
使用隐式函数参数
除了在函数定义中显示声明的参数之外,函数调用时还会传递两个隐式参数:arguments和this。这些隐式参数在函数声明中没有明确定义,但会默认传递给函数并且可以在函数内正常访问。在函数内可以像其他明确定义的参数一样引用它们。
arguments参数
arguments参数是传递给函数的所有参数的集合。无论是否有明确定义对应的形参,通过它我们可以访问到函数的所有参数。借此可以实现原生JavaScript并不支持的函数重载的特性,而且可以实现接收参数数量可变的可变函数。
arguments对象有一个名为length的属性,表示实参的确切个数。通过数组索引的方式可以获取单个参数的值,例如,arguments[2]将获取第三个参数。
console.log("---------------------使用arguments参数----------------------");
//声明一个函数,具有3个形参:a、b、c
function whatever(a, b, c) {
//值的准确性校验
if (a === 1) {
console.log("The value of a is 1");
}
if (b === 1) {
console.log('The value of b is 2');
}
if (c === 3) {
console.log("The value of c is 3");
}
if (arguments.length === 5) {
console.log("We have passed in 5 paramters");
}
//验证传入的前三个实参与函数的3个形参匹配
if (arguments[0] === a) {
console.log('The first argument is assigned to a');
}
if (arguments[1] === b) {
console.log('The second argument is assigned to b');
}
if (arguments[2] === c) {
console.log('The third argument is assigned to c');
}
//验证额外的参数可以通过参数arguments获取
if (arguments[3] === 4) {
console.log("We can access the fourth argument");
}
if (arguments[4] === 5) {
console.log("We can access the fifth argument");
}
}
//调用函数时传入五个参数
whatever(1,2,3,4,5);
即使这里的whatever函数只定义了3个形参,但在调用的时候传入了5个参数:
whatever(1,2,3,4,5);
//声明一个函数,具有3个形参:a、b、c
function whatever(a, b, c) {
... ...
}
//我们可以通过相应的函数参数a、b和c访问到前面3个参数的值:
if (a === 1) {
console.log("The value of a is 1");
}
if (b === 1) {
console.log('The value of b is 2');
}
if (c === 3) {
console.log("The value of c is 3");
}
我们可以使用arguments.length属性来获取传递给函数的实际参数的个数。
通过数组下标的方式还可以访问到arguments参数中的每个参数值。值得注意的是,这里也包括没有合函数形参相关联的剩余参数。
//验证传入的前三个实参与函数的3个形参匹配
if (arguments[0] === a) {
console.log('The first argument is assigned to a');
}
if (arguments[1] === b) {
console.log('The second argument is assigned to b');
}
if (arguments[2] === c) {
console.log('The third argument is assigned to c');
}
//验证额外的参数可以通过参数arguments获取
if (arguments[3] === 4) {
console.log("We can access the fourth argument");
}
if (arguments[4] === 5) {
console.log("We can access the fifth argument");
}
即使这里的whatever函数只定义了3个形参,但在调用的时候传入了5个参数:
要避免把arguments参数当做数组。不要被arguments的用法误导,毕竟它有length属性,而且可以通过数组下标的方式访问到每个元素。但它并非是JavaScript数组,如果你尝试在arguments对象上使用数组方法,比如数组的sort方法,发现最终会报错。
arguments对象仅是一个类数组的结构。
arguments对象主要作用是允许我们访问传递给函数的所有参数,即便部分参数没有和函数的形参关联也无妨。
参考《JavaScript忍者秘籍》