本文共 635 字,读完只需 3 分钟javascript
JavaScript中的函数与其余面向对象语言有几个不一样的地方。java
简单来讲,JAVA 同一个类中容许几个函数有一样的函数名称,可是参数声明不同,这就是函数重载。数组
可是 JS 不支持函数重载:闭包
function foo(num) {
console.log(num + 100)
}
function foo(num) {
console.log(num + 200)
}
foo(100); // 300
复制代码
若是 js 中定义了两个相同名称的函数,那么该名字只属于后定义的那个函数。app
函数 arguments 对象是全部(非箭头)函数中均可用的局部变量, 是一个相似数组的对象。你可使用arguments对象在函数中引用函数的(实际)参数。函数
function foo() {
console.log(arguments);
}
foo(1, "foo", false, {name: "bar"}); // [1, "foo", false, object]
复制代码
function foo() {
console.log(typeof arguments);
}
foo(1, "foo", false, {name: "bar"}); // object
复制代码
因此,arguments 是一个具备数组样式的对象,有 length 属性,和下标来索引元素。post
lengthui
function foo(num1, num2, num3) {
console.log(arguments)
}
foo(1); // [1]
复制代码
length 属性表示传入函数的实际参数数量,而不是函数声明时的形参数量。this
callee
callee 表示函数自己,咱们能够在函数中经过 callee 调用自己。spa
复制代码
arguments 对象不支持数组的其余方法,可是能够用 Function.call 来间接调用。
function sayHi() {
console.log(Array.prototype.slice.call(arguments, 0))
}
sayHi("hello", "你好", "bonjour") //["hello", "你好", "bonjour"]
复制代码
function sayHi() {
console.log(Array.prototype.splice.call(arguments, 0));
}
sayHi("hello", "你好", "bonjour") //["hello", "你好", "bonjour"]
复制代码
function sayHi() {
console.log(Array.from(arguments));
}
sayHi("hello", "你好", "bonjour") //["hello", "你好", "bonjour"]
复制代码
function sayHi(...arguments) {
console.log(arguments);
}
sayHi("hello", "你好", "bonjour") //["hello", "你好", "bonjour"]
复制代码
严格模式和非严格模式中,arguments 的表现显示不相同。
// 严格模式
function foo(a, b) {
"use strict";
console.log(a, arguments[0]);
a = 10;
console.log(a, arguments[0]);
arguments[0] = 20;
console.log(a, arguments[0]);
b = 30;
console.log(b, arguments[1])
}
foo(1);
输出:
1 1
10 1
10 20
30 undefined
// 非严格模式
function foo(a, b) {
console.log(a, arguments[0]);
a = 10;
console.log(a, arguments[0]);
arguments[0] = 20;
console.log(a, arguments[0]);
b = 30;
console.log(b, arguments[1]);
}
foo(1);
输出:
1 1
10 10
20 20
30 undefined
复制代码
在非严格模式中,传入的参数,实参和 arguments 的值会共享,当没有传入时,实参与 arguments 值不会共享。
而在严格模式中,实参和 arguments 的值不会共享。
欢迎关注个人我的公众号“谢南波”,专一分享原创文章。