Two practical methods for parsing the Function defined in JS

Source: Internet
Author: User

This article describes the two methods that are commonly used to define functions in JS. Although the results of Function calls defined in the two methods are the same, there are still differences between them, I believe this article will surely help you gain some benefits.

JS is a very common method for defining functions.

We all know that Javascript has two Function-defining methods that are very common.

For example

 
 
  1. functiona(){alert("a")}  
  2.  
  3. vara=function(){alert("a")}  

Although the results of function calls defined by the two methods are the same, there are still differences between them. For example, if we want to redefine a (), and the new method must inherit all the methods in a () and perform other extensions. The difference between the two methods is obvious.

1. First, create a temporary variable to store ()

 
 
  1. varb=a;  
  2.  

Then, redefine ()

Method 1:

 
 
  1. functiona(){  
  2. b();  
  3. alert("ok");  

Method 2:

 
 
  1. a=function(){  
  2. b();  
  3. alert("ok");  

This is something you can try to find. The first way to redefine a () will cause a stack overflow error. In the second method, the script executed by a () is successfully retained, and alert prompts "a" "OK", indicating that () is redefined.

Here we can clearly distinguish between the two methods. The order of definition is different.

First, the function a was not re-defined at the beginning and the function itself was executed in it.

In the second way, a = function () is not executed here. Code a in the function has been redefined. So the definition here is valid.


 

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.