How to use this in JS
This is one of the most powerful keywords in JavaScript. Unfortunately, if you don't know exactly how it works, you'll have a hard time using it correctly.
This is an important concept in Object-oriented languages. In large languages such as JAVA and C#, this fixedly points to the current object at runtime. But in javascript, due to the dynamic nature of javascript (interpretation and execution, of course, there is also a simple pre-compilation process), the point of this is determined only at runtime. This feature not only brings confusion to us, but also brings freedom and flexibility in programming. Combined with the apply (call) method, it can make JS extremely powerful.
2. Changed this
In JavaScript, this usually points to the function itself that we are executing, or to the object to which the function belongs (runtime). When we define the function doSomething() in the page, its owner is the page, or the window object (or global object) in JavaScript. For an onclick attribute, it is owned by the HTML element to which it belongs, and this should point to the HTML element.
2.1 Changes to this in several common scenarios
Function examples
function doSomething () { alert(this.navigator); //appCodeName this.value = "I am from the Object constructor"; this.style.backgroundColor = "# 000000"; }
1. (A) When called directly as a normal function, this points to the window object.
2. (B) When triggered as a control event
1) inline event registration. Register the event directly. Written in HTML code (
2) Traditional event registration Traditional event registration (DHTML method).
Form like element.onclick = doSomething; At this time this points to the element object
3)
4. (D) When using the apply or call method, this points to the passed object.
Form: var obj={}; doSomething.apply(obj,new Array(”nothing”); //thisàobj
Let me explain how to handle eventsUse this in, I will attach some examples related to this later
Owner
The question we will discuss in the next article is: what does this refer to in the function doSomething(). ?
Javascript code
function doSomething() {
this.style.color = '#cc0000';
}
function doSomething() {
this.style.color = ' #cc0000';
}
In JavaScript, this usually points to the function itself that we are executing (Translator's Note: Use owner to represent what this points to), or to the object to which the function belongs. . When we define the function doSomething() in the page, its owner is the page, or the window object (or global object) in JavaScript. For an onclick attribute, it is owned by the HTML element to which it belongs. It should point to the HTML element.
This kind of "ownership" is a way of object-oriented in JavaScript. You can see some more information in Objects as associative arrays ##If we are in. If doSomething() is executed without any further preparation, the this keyword will point to window, and the function attempts to change the window's style.color. Since window does not have a style object, this function will unfortunately fail and generate a JavaScript error. .
Copying
So if we want to make full use of this, we have to pay attention that the function using this should be owned by the correct HTML element. In other words, we should copy this function to our onclick event attribute. registration will care about it.
Javascript code
element.onclick = doSomething;
element.onclick = doSomething;
This function is completely copied to the onclick attribute (now it becomes a function). The handler is executed, this will point to the HTML element, and the color of the element is changed.
This method allows us to copy this function to multiple event handlers. This will point to the correct HTML element every time:
This way you can maximize the use of this. Whenever this function is executed, the HTML elements pointed to by this respond to the event correctly, and these HTML elements have a copy of doSomething().
Referring
However, if you use inline event registration (inline event registration)
Javascript code
You will not be able to copy this function! On the contrary, this difference is very critical. The onclick attribute does not contain an actual function, just a function call.
Javascript code
doSomething();
doSomething();
So, it will state "go to doSomething() and execute it". When we reach doSomething(), the this keyword points to the global window object again, and the function returns
error message.
The difference
If you want to use this to point to the event that the HTML element responds to, you must ensure that the this keyword is written in the onclick attribute. Only in this case does it point to the HTML element registered by the event handler.
Javascript code
element.onclick = doSomething;
alert(element.onclick)
element.onclick = doSomething;
alert(element.onclick)
You will get
Javascript code
function doSomething() {
this.style.color = '#cc0000';
}
function doSomething() {
this.style.color = '#cc0000';
}
As you can see, the this keyword is displayed in the onclick function, so it points to the HTML element.
But if
Javascript code is executed
alert(element.onclick)
alert(element.onclick)
You will get
Javascript code
function onclick() {
doSomething()
}
function onclick() {
doSomething()
}
This is just a reference to the doSomething() function. The this keyword does not appear in the onclick function, so it does not point to the HTML element.
Example--Copy
In the following example, this is written into the onclick function:
Javascript code
element.onclick = doSomething
element.addEventListener('click', doSomething, false )
element.onclick = function() {this.style.color = '#cc0000';}
element.onclick = doSomething
element.addEventListener('click', doSomething, false)
element.onclick = function() {this.style.color = '#cc0000';}
Example--Quote
In the following situation, this points to window:
Javascript code
element.onclick = function() {doSomething()}
element.attachEvent('onclick', doSomething)
element.onclick = function() {doSomething()}
element.attachEvent('onclick', doSomething)
Pay attention to the appearance of attachEvent(). The main drawback of the Microsoft event registration model is that attachEvent() creates a reference to the function instead of copying it. So sometimes it's impossible to know which HTML is handling the event.
Combined use
When using inline event registration, you can send this to the function so that it can be used normally:
Javascript code
function doSomething(obj) {
//This appears in the event handler and is sent to the function
//obj points to the HTML element, so it can be like this:
obj.style.color = '# cc0000';
}
The above is the detailed content of How to use this in JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Classification and Usage Analysis of JSP Comments JSP comments are divided into two types: single-line comments: ending with, only a single line of code can be commented. Multi-line comments: starting with /* and ending with */, you can comment multiple lines of code. Single-line comment example Multi-line comment example/**This is a multi-line comment*Can comment on multiple lines of code*/Usage of JSP comments JSP comments can be used to comment JSP code to make it easier to read

How to use the exit function in C language requires specific code examples. In C language, we often need to terminate the execution of the program early in the program, or exit the program under certain conditions. C language provides the exit() function to implement this function. This article will introduce the usage of exit() function and provide corresponding code examples. The exit() function is a standard library function in C language and is included in the header file. Its function is to terminate the execution of the program, and can take an integer

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

How to use Apple shortcut commands With the continuous development of technology, mobile phones have become an indispensable part of people's lives. Among many mobile phone brands, Apple mobile phones have always been loved by users for their stable systems and powerful functions. Among them, the Apple shortcut command function makes users’ mobile phone experience more convenient and efficient. Apple Shortcuts is a feature launched by Apple for iOS12 and later versions. It helps users simplify their mobile phone operations by creating and executing custom commands to achieve more efficient work and

Detailed explanation of distinct usage in SQL In SQL databases, we often encounter situations where we need to remove duplicate data. At this time, we can use the distinct keyword, which can help us remove duplicate data and make the query results clearer and more accurate. The basic usage of distinct is very simple, just use the distinct keyword in the select statement. For example, the following is a normal select statement: SELECTcolumn_name

Usage of Transform in CSS The Transform property of CSS is a very powerful tool that can perform operations such as translation, rotation, scaling and tilting of HTML elements. It can dramatically change the appearance of elements and make web pages more creative and dynamic. In this article, we will introduce the various uses of Transform in detail and provide specific code examples. 1. Translate (Translate) Translate refers to moving an element a specified distance along the x-axis and y-axis. Its syntax is as follows: tran
