Home >Web Front-end >JS Tutorial >Introduction to the definitions and differences between the two functions of javascript_javascript skills

Introduction to the definitions and differences between the two functions of javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:34:571062browse

Generally speaking, the results of the two calls are the same, but there are still differences.
First way:

Copy code The code is as follows:

function a() {
alert('old');
}
var b=a;
function a(){
b();
alert('new');
}
a();//The browser will experience memory overflow

Second way:
Copy Code The code is as follows:

function a(){
alert('old');
}
var b=a;
var a=function(){
b();
alert('new');
}
a();//The browser will alert 'old' in order and 'new'

The difference between the two methods can be clearly distinguished here. The order of definition is different.
The first one is that the function a is not redefined at the beginning but is executed inside it.
The second way, a = function () where the code a that is not executed into the function has been redefined. So the redefinition here is valid
Supplement 1:
Copy the code The code is as follows:

function a(){
alert('old');
}
var b=a;
function a(){
b();
alert(' new');
}

When compiling: first a is defined as alert("old"), and then it is defined as b();alert("new");
Runtime: b = function a(){b();alert("new");}, at this time b is the same as a, b is called directly in the function body, and the result is the same whether called from a or b. Produces stack overflow
On the other hand
Copy the code The code is as follows:

function a( ){
alert('old');
}
var b=a;
var a=function(){
b();
alert('new') ;
}

Compile time: a is defined as alert("old")
Run time: b=function a(){alert("old")}; a= function(){b();alert("new")}; At this time, the function body of b does not include any of ab, and a only calls b... No stack overflow will occur in any case...
Supplement 2:
Generally speaking, the first way of writing is used to avoid code pollution, but if you need to retain the original function, you must use the second way of writing. Anyway, both methods are in compliance with w3c.
In fact, the first way of writing came later, and this way of writing has been optimized.
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