Home >Web Front-end >JS Tutorial >Summary of three ways to define functions in JavaScript_javascript skills

Summary of three ways to define functions in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:44:161195browse

(1) Declare an expression variable and define the expression of the variable. For example:

Copy code The code is as follows:

var func = function()
{
/*body code*/
}

(2) Define a function expression and specify the identifier of the expression. For example:
Copy code The code is as follows:

function func()
{
//body code
}

(3) Use JavaScript built-in Function object construction. For example:
Copy code The code is as follows:

var func = new Function("/*parameters */","/*body code*/");

There is a difference between declaring variable definitions and using function expressions to identify definitions. We know that function uses a reference transfer type when passing. The use of variable definition saves the address reference of the expression, and the use of flag definition saves the address of the expression. Therefore, when we change or redefine a variable, it will not cause the original expression to change; and when we change the identifier, its corresponding expression will also change. For example:
Copy code The code is as follows:

//Declare a variable and define the variable Expression reference
var test = function()
{
alert("reference test");
}
//Define an expression and save its address information in test1
function test1()
{
alert("reference test1");
}
//Pass the expression referenced by test to reference
var reference = test;
//Pass the address of the test1 expression to reference1
var reference1 = test1;
//Change the reference of the variable test
test = function()
{
alert("new test ");
}
//Redefine the data in the test1 address
function test1()
{
alert("new test1");
}
alert( reference);//The expression it refers to does not change
alert(reference1);//Since reference1 is a reference to the test1 address, when the content represented by the test1 address changes, the content of reference1 also changes
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn