Home Web Front-end JS Tutorial Questions about whether there are parentheses after the event processing function name in JS

Questions about whether there are parentheses after the event processing function name in JS

Dec 06, 2016 pm 04:00 PM
js

Today I summarize a small detail about event handlers. First, let’s review some concepts of event processing.

 Event processing (event binding) in JS is to let some or certain events trigger certain activities. There are two common forms, namely DOM Level 0 and DOM Level 2. The biggest difference between these two methods is that DOM level 0 event processing can only be used for event bubbling, while DOM level 2 event processing can support event bubbling and event capture respectively by setting the third parameter.

  DOM level 0 event processing generally assigns a function to an event handler directly. You can assign an event handler directly to the element, as shown in method 1; you can also assign the function to the event handler in the script. , as shown in method two.

<!--方式一-->
<div onclick="fun1();fun2(&#39;world!&#39;);"></div>
<!--方式二-->
<div id="a">点我</div>
<script>
var a=document.getElementById("a");
a.onclick=fun1; //方式二
function fun1(){
alert("hello!");
}
function fun2(cc){
alert(cc);
}
</script>
Copy after login

The difference between the two methods is also shown in the above example. The first method can bind multiple processing functions at the same time, but please note that it must be a global function, otherwise a Reference error will be thrown. The second method can only bind one processing function at a time, otherwise the new function will overwrite the old function.

  DOM level 2 event processing does not directly bind the processing function, but adds the function as an event listener as follows. It can also bind multiple processing functions without overwriting. However, this method has browser compatibility issues, and the attachEvent method must be used instead under IE.

a.addEventListener("click",fun1,false); //事件冒泡
a.addEventListener("click",anotherFun,false); //不会覆盖上一事件,均被执行
Copy after login

That’s it for a brief review, let’s get back to the topic. I wonder if you have noticed a confusing little detail during the review process, that is, when referencing a function, sometimes parentheses are added after the function name. without adding parentheses. How does this affect the operation of the program? I have briefly summarized the following based on my own understanding after consulting the information.

The first thing is to add parentheses. You may often write "fun1();" in a program. Yes, adding parentheses after the function name means executing the function immediately. If the return value exists in the function memory, the value will be obtained. If you use this a lot, you may get used to writing it like this in all places where functions are called, such as the event handling function mentioned before. However, if you do this it can cause some out of control situations. For example, you obviously only want to execute a function when you click on an element, but you find that the function is executed at the beginning. You can find that the DOM0 mode 2 and DOM2 level event processing functions used in the above example do not add parentheses after the function name, the reason is to avoid this situation. If you add parentheses, the function fun1 will be triggered and executed immediately.

Then why are there brackets in DOM0 method one? That's because the quotes between the tag's event attributes will be directly executed as js statements. Only by adding parentheses can the function be called and executed. However, since the event is bound using an element tag, the timing of execution is controlled to be triggered when the tag is clicked.

 What if there is no function name and you want to execute it immediately? That is, the anonymous function expression is executed immediately. This mode is very common. Let’s see if there is an immediate execution parentheses behind it? Note that the parentheses surrounding the entire function body in this IIFE form limit the scope. Children's shoes who are specifically interested in IIFE can check the relevant information. I will not go into details here.

(function(){
//do something...
})();
Copy after login

Now let’s analyze the one without parentheses. We mentioned earlier that not adding parentheses can avoid getting out of control. This is because passing only the function name to the event is equivalent to passing the function pointer (that is, the entry address of this function) to the element event. The advantage of this is that the function can be found and executed when needed. To use a small metaphor, when you meet your friend, when you add parentheses, your friend will immediately appear in front of you. He doesn't care whether you are busy at the time, and there is an uninvited and unpleasant feeling; Not adding parentheses is equivalent to your friend telling you where his home is and coming to him when you need him. This is really a considerate friend. Therefore, most event bindings just pass a function pointer, which is the function name, to the event.

There is another question at this time. The functions explained before are all parameterless functions. What if it is a parameterized function like fun2 in the code example? Can we only use DOM0 method one? Of course it is negative. Try not to use DOM0 mode one, which does not comply with the principle of separation of structure and behavior. Generally, this situation is solved by using anonymous functions, as shown in the following code. If you have any good suggestions, you can leave a message and share them~

//DOM Level 0
a.onclick=function(){
fun2("world!");
};
//DOM Level 2
a.addEventListener("click",function(){fun2("world!");},false);
Copy after login

​​​


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles