Home > Web Front-end > JS Tutorial > Detailed explanation of the difference between using function statements and expressions to define functions in javascript_javascript skills

Detailed explanation of the difference between using function statements and expressions to define functions in javascript_javascript skills

WBOY
Release: 2016-05-16 17:05:28
Original
1180 people have browsed it

I have been using JavaScript for many years and have written countless functions. But today I really understand the difference between the two function definitions. It is really tragic. I wrote this essay to remind myself to lay a good foundation. I am too old to continue. I understand.

Usually we see the following two ways of defining functions:

Copy code The code is as follows:

// Function statement
function fn(str)
{
console.log(str);
};

//Expression definition
var fnx=function(str)
{
console.log(str ' from fnx');
};


In the past, I used the two as I wanted based on the feeling of my fingers -_- ||. Today, after reading the basics of js, I finally solved my confusion about them:

Both methods create new function objects, but the function name in the function declaration statement is a variable name, and the variable points to the function object. Just like declaring variables through var, the function in the function definition statement is explicitly advanced to the script. or the top of the function, so they are visible throughout the script and within the function, but using var expressions to define functions, only the variable declarations are brought forward, the variable initialization code is still in the original place, the function created with the function statement, the function name and the function body are prepended so we can use it before declaring it.

The code example is as follows:

Copy the code The code is as follows:

console.log(typeof(fn)); // function
fn('abc'); // abc


console.log(typeof(fnx)); // undefined

if(fnx)
fnx('abc'); // will not execute
else
console.log('fnx is undefined'); // fnx is undefined

// Function statement
function fn(str)
{
console.log(str);
};

// Expression definition
var fnx=function(str)
{
console.log(str ' from fnx');
};


The code is very simple. I hope that students who haven't figured out the difference between the two like me before can gain something.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template