Functions in JavaScript differ from other object-oriented languages in several ways.
There is nofunction overloading
There is an array-like object arguments
## that represents the actual parameter listfunction foo(num) { console.log(num + 100) } function foo(num) { console.log(num + 200) } foo(100); // 300
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
3. Attributes of arguments
length
function foo(num1, num2, num3) { console.log(arguments) } foo(1); // [1]
calleecallee represents the function itself, we can call itself through callee in the function.
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"]
// 严格模式 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
In non-strict mode, the values of passed parameters, actual parameters and arguments will be shared. When nothing is passed in, the actual and arguments values will not be shared.
In strict mode, the values of actual parameters and arguments are not shared.
The above is the detailed content of Detailed explanation of arguments function in JavaScript (with examples). For more information, please follow other related articles on the PHP Chinese website!