search
HomeWeb Front-endJS TutorialHow to use this in JS

How to use this in JS

Jul 07, 2017 pm 03:02 PM
javascriptthisusage

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 (onclick=”doSomething()”>), at this time this points to the window object.
2) Traditional event registration Traditional event registration (DHTML method).
Form like element.onclick = doSomething; At this time this points to the element object
3) 3. (C) When used as an object, this points to the current object. The form is: new doSomething();
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
How to use this in JS##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.

How to use this in JSThis method allows us to copy this function to multiple event handlers. This will point to the correct HTML element every time:

How to use this in JSThis 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.
How to use this in JSThe 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!

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)