Deep understanding of JavaScript function parameters (recommended) _javascript tips

Source: Internet
Author: User
Tags function definition

Front.

The parameters of a JavaScript function differ from those of the functions in most other languages. The function does not mind passing in the number of arguments, nor does it care what data type the incoming parameter is, or even the parameters.

Arguments

The function definition in JavaScript does not specify the type of the function parameter, nor does the function call check any type of the passed argument value. In fact, JavaScript function calls do not even check the number of incoming formal parameters

function Add (x) {return
x+1;
}
Console.log (Add (1)),//2
console.log (Add (' 1 '));//'
Console.log ' (Add ());//nan
Console.log (Add (1,2 ));//2

Formal parameters with the same name

In a non-strict mode, a parameter with the same name can appear in a function and can only access the last formal parameter of the name that appears

function Add (x,x,x) {return
x;
}
Console.log (Add (1,2,3));//3

In strict mode, the presence of the same name in the form of a participant throws a syntax error

function Add (x,x,x) {
' use strict ';
return x;
}
Console.log (Add (1,2,3));//syntaxerror:duplicate parameter name not allowed in the context

Number of parameters

When an argument is less than the number of formal parameters specified by a function declaration, the remaining formal parameters are set to the undefined value

function Add (x,y) {
console.log (x,y);//1 undefined
}
Add (1);

A logical OR operator is often used to set a reasonable default value for an omitted parameter

function Add (x,y) {
y = y | | 2;
Console.log (x,y);//1 2
}
Add (1);

[note] Actually, use y | | 2 is not rigorous and the same result is achieved by explicitly setting false values (undefined, null, FALSE, 0,-0, ', NaN '). So it should be set up according to the actual scene

When the argument is more than the number of parameters, the remainder of the argument is not directly available, and the arguments object to be referred to will be used

The parameters in JavaScript are represented internally by an array. This array is always received by the function, and does not care what parameters are included in the array. This parameter array can be accessed by the arguments object in the function body to obtain each argument passed to the function. The arguments object is not an instance of an array, it is a class array object, and you can access each of its elements using the square brackets syntax

function Add (x) {
console.log (arguments[0],arguments[1],arguments[2])//1 2 3 return
x+1;
}
Add (1,2,3);

The length property of the arguments object displays the number of arguments, and the length property of the function displays the number of formal parameters

function Add (x,y) {
console.log (arguments.length)//3 return
x+1;
}
Add (1,2,3);
Console.log (add.length);//2

Formal parameters are only convenient, but not required

function Add () {return
arguments[0] + arguments[1];
}
Console.log (Add (1,2));//3

Object parameters

When a function contains more than 3 formal parameters, it is a headache to remember that the correct order of the arguments in the calling function is really annoying.

function Arraycopy (/*array*/from,/*index*/form_start,/*array*/to,/*index*/to_start,/*integer*/length) {
// Todo
}

Passing parameters in the form of a name/value pair, so that the order of the parameters is irrelevant. When you define a function, the incoming arguments are written to a separate object, and an object is passed in at the time of the call, and the name/value pairs in the object are the actual parameters that are really needed.

function EasyCopy (args) {
arraycopy (Args.from,args.form_start | | 0,args.to,args.to_start | | 0, args.length);
}
var a = [1,2,3,4],b =[];
EasyCopy ({form:a,to:b,length:4});

Synchronous

When the form participates in the number of arguments, the value of the arguments object and the value of the corresponding parameter are kept in sync

function test (num1,num2) {
console.log (num1,arguments[0]);//1 1
arguments[0] = 2;
Console.log (Num1,arguments[0]);//2 2
num1 = ten;
Console.log (Num1,arguments[0]);//10
Test (1);

[note] Although the value of the named parameter and the corresponding arguments object is the same, it is not the same namespace. Their namespaces are separate, but the values are synchronized

In strict mode, however, the value of the arguments object and the value of the formal parameter are independent

function test (num1,num2) {
' use strict ';
Console.log (Num1,arguments[0]);//1 1
arguments[0] = 2;
Console.log (Num1,arguments[0]);//1 2
num1 = ten;
Console.log (Num1,arguments[0]);//10 2
}
Test (1);

When a formal parameter does not have a corresponding argument, the value of the arguments object does not correspond to the value of the formal parameter

function test (num1,num2) {
console.log (num1,arguments[0]);//undefined,undefined
num1 = ten;
Arguments[0] = 5;
Console.log (Num1,arguments[0]);//10,5
}

Internal properties

"Callee"

The arguments object has a property named Callee, which is a pointer to the function that owns the arguments object

Here's the classic factorial function.

function factorial (num) {
if (num <=1) {return
1;
} else{return
num* factorial (num-1);
} 
Console.log (factorial (5));//120

However, the execution of the above function is tightly coupled to the function name, and you can use Arguments.callee to eliminate the function decoupling

function factorial (num) {
if (num <=1) {return
1;
} else{return
num* Arguments.callee (num-1);
} 
Console.log (factorial (5));//120

But in strict mode, accessing this property throws a TypeError error

function factorial (num) {
' use strict ';
if (num <=1) {return
1;
} else{return
num* Arguments.callee (num-1);
} 
TypeError: ' Caller ', ' callee ', and ' arguments ' properties may is accessed on strict mode functions or the arguments Objects for calls to them
Console.log (factorial (5));

At this point, you can make the function expression of the appliance name

var factorial = function fn (num) {
if (num <=1) {return
1;
} else{return
NUM*FN (num-1);
}
; 
Console.log (factorial (5));//120

"Caller"

There are actually two caller properties

The caller of the "1" function

The caller property of the function holds a reference to the function that called the current function, and if the current function is called in the global scope, its value is null

function outer () {
inner ();
}
function inner () {
console.log (inner.caller);//outer () {inner ();}
}
Outer (); 
function inner () {
console.log (inner.caller);//null
}
inner ();

In strict mode, accessing this property throws a TypeError error

function inner () {
' use strict ';
TypeError: ' Caller ' and ' arguments ' are restricted function properties and cannot is accessed in the context
Conso Le.log (Inner.caller);
}
Inner ();

The caller of the "2" arguments object

This property is always undefined, which is defined to distinguish Arguments.caller and function caller properties

function inner (x) {
console.log (arguments.caller);//undefined
}
inner (1);

Similarly, in strict mode, accessing this property throws a TypeError error

function inner (x) {
' use strict ';
TypeError: ' Caller ' and ' arguments ' are restricted function properties and cannot is accessed in the context
Consol E.log (Arguments.caller);
}
Inner (1);

Function overload

JavaScript functions do not implement overloads as they are traditionally meant. In other languages, you can write two definitions for a function, as long as the signatures of the two definitions (the type and number of parameters accepted) are different.

A JavaScript function has no signature because its arguments are represented by an array that contains 0 or more values. Without a function signature, the real overload is impossible.

The following declaration overrides the previous declaration
function Addsomenumber (num) {return
num +;
}
function Addsomenumber (num) {return
num +
}
var result = Addsomenumber (100);//300

You can mimic the overload of a method only by examining the type and number of parameters in the incoming function and reacting differently

function Doadd () {
if (arguments.length = 1) {
alert (arguments[0] +);
} else if (arguments.length = = 2) {
alert (Arguments[0] + arguments[1])
;
}
Doadd (a);//20
Doadd (30,20);//50

Parameter passing

Parameters for all functions in JavaScript are passed by value. That is, copying the values from outside the function to the parameters inside the function is the same as copying the value from one variable to another

"1" Basic type value

When a value of the base type is passed to a parameter, the passed value is copied to a local variable (named argument or an element of the arguments object)

function Addten (num) {
num = ten;
return num;
}
var count =;
var result = Addten (count);
Console.log (count);//20, no change
console.log (result);//30

"2" Reference type value

When passing a value of a reference type to a parameter, the value in memory is copied to a local variable, so the change of the local variable is reflected outside the function

function SetName (obj) {
obj.name = ' Test ';
}
var person = new Object ();
SetName (person);
Console.log (person.name);//' Test '

When you override a reference type's formal parameter inside a function, the variable refers to a local object. And this local object will be destroyed immediately after the function has been executed.

function SetName (obj) {
obj.name = ' Test ';
Console.log (person.name);//' Test '
obj = new Object ();
Obj.name = ' white ';
Console.log (person.name);//' Test '
}
var person = new Object ();

The above is a small set for you to introduce the in-depth understanding of JavaScript function parameters (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.