Home > Web Front-end > JS Tutorial > body text

Variable function declaration priority in Javascript

黄舟
Release: 2017-03-01 14:32:30
Original
1493 people have browsed it

Case One

console.log(a); //输出function a(){}
function a() {};
var a=3;
Copy after login

Case Two

function a() {};
var a=3;
console.log(a);//输出3
Copy after login


Why are the outputs of the two different?

Analysis:

For case one

The execution process can be refined as

#1. First, it will apply for a space, start to declare function a, and then declare variable a during execution , it is found that there is already a declaration of a, so no declaration is made

2. Then, console.log(a) is executed; that is, the output function a

#3. The final execution is to perform the assignment operation, and set a=3. At this time, the function a is converted to a variable type and assigned a value of 3. For verification, you can change the program to the following

#

a();
function a() {
	console.log(5);
};
var a=3;
a();
Copy after login

You can find that the program execution results are as follows:


##Because before the assignment, a is still a function. After the assignment statement is executed, a It becomes 3, and an error will be reported when executing a().

For Case 2

# #Similarly, it can be seen that function a is first declared, then declares variable a, and finds that there is already a declaration of a, so it does not declare it. Next, the assignment statement is executed to convert function a into a variable. Finally output the value of variable a

Summary:

1)函数被申明的优先级高于变量

2)被声明过的变量名或是函数名不会被重复申明

3)变量和赋值语句一起书写,在js引擎解析时,会将其拆成声明和赋值2部分,声明置顶,赋值保留在原来位置


补充

1.下面代码执行结果为

var x=0;
f();
console.log(x);
var f=function(){
	x=1;
}
f();
console.log(x);
function f(){
	x=2;
}
f();
console.log(x);
Copy after login


答案:2 1 1 

 以上就是Javascript中变量函数申明优先级的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!