


In-depth understanding of the scope of this in Javascript_javascript skills
Everyone is often confused by this guy when using Javascript. For most developers with OOP development experience, this is an identifier that refers to ordinary elements in the current scope, but in Javascript it seems weird because it is not fixed, but changes with it. changes due to changes in the execution environment. In Javascript this always points to the object on which the method is called.
Give a simple example:
function test(){
alert(this);
}
var obj=function(){
var name='testObj';
}
obj.objTest=test;
test();
obj.objTest();
Put this code into HTML and run this page. You will see a warning [object window] first, and then a second warning.
var obj=function(){
var name='testObj';
}
We first defined a test() method, and called the alert() method inside the method to display this. Then we defined an obj function object, added a private field name to it, and added A static method objTest() is created, and this function points directly to the test() function.
Call the test() and obj.objTest() methods respectively. The first warning box prompts the Window object, and the second prompt is the code of the obj function we defined. This shows that the value of this is different when the test function is executed twice!
This shows that when the object calling the function is different, the object referred to by the internal this keyword is different. It should be noted here that Javascript is an object-based language. When our variables or functions are defined under the root of the <script></script> tag, it is actually equivalent to adding corresponding attributes or methods to the window object. So when we use the function test(){} code to define a function, it is actually equivalent to adding a new function to the window object, namely the window.test() function.
We can do an experiment:
function test(){
alert(this);
}
alert(test===window.test);
The warning box prompt will be true, which means that when we call the test() function, we are equivalent to calling window.test(). So when we call the test() function, the object that calls this function is actually the window object, and this refers to the window object, so the content of the warning window that pops up when we alert(this) is [object Window]. We set obj.objTest=test which is equivalent to pointing obj.objTest() to test(), so when we call the obj.objTest() function, it is equivalent to calling the test() function in obj, so now this refers to obj object, what is prompted is the function of obj, which is the code we see.
This should be explained almost enough. Maybe the above example is too abstract and I can’t imagine the circumstances in which it can be used. So let’s assume a requirement now and make a more practical example.
Suppose that the color of all hyperlinks in our current page should be changed to red after being clicked, and this is implemented using Javascript. The general idea should be to get all the tags in the page, then traverse all the tags, and register a click event for each one. After the event is triggered, we set its color value to red.
The sample code is as follows:
//Change color
function changeColor(){
this.style.color='#f00';
}
//Initialize, register events for all a tags
function init(){
var customLinks=document.getElementsByTagName('a');
for(i in customLinks){
//You can also use event listeners to register events
//Due to compatibility with IE, FF and other browsers, more code may be required, you can write it yourself
customLinks[i].onclick=changeColor;
}
}
window.onload=init;
Add this code to the HTML document and add some hyperlinks to the document. When the hyperlink is clicked, the color will turn red. The this keyword in the changeColor() function we defined here is triggered when the hyperlink is clicked. function, it refers to the current hyperlink. And if you call the changeColor() function directly, the browser will report an error, prompting an error such as Error: ‘this.style’ is null or not an object or undefined.
I wonder if this can give you who are reading the article some understanding of the this keyword in Javascript? Or are you impatient? (:P)
In fact, if you want to truly have a deeper understanding of this issue, you must have a deep understanding of the scope and scope chain of Javascript.
Scope, as the name suggests, refers to the code space that a certain attribute or method has access permissions. Simply put, it is the scope of application of this variable or method in the code. In most OOP, there are three main scopes: public, private, and protect. I will not explain the three scopes in detail here. If you have OOP experience, you should have an in-depth understanding of them. What I want to say here is that these three scope types are almost meaningless to Javascript, because there is only one public scope in Javascript, and scopes in Javascript are maintained within functions. For example:
var test1='globle variable';
function example(){
var test2='example variable';
alert(test1);
alert(test2);
}
example();
alert(test1);
alert(test2);
According to what we explained earlier, the test1 variable here is equivalent to an attribute of window, so it will work within the entire window scope, while test2 is declared inside the example() function, so its scope is Maintained inside the example() method, if the test2 browser is called outside the function, an error will be prompted. There is no problem calling test1 inside example().
Based on this, let’s give another example:
var test='globle variable';
function example(){
var test='example variable';
}
example();
alert(test);
What will be the result of running this example? Yes, the warning box will prompt "globle variable" because the scope of the test variable inside the example() function only remains internal and will not affect the external test variable. What if we remove the var keyword from the test variable inside example()? You can try it yourself.
Speaking of this, another concept is involved, that is, the concept of scope chain. A scope chain is a path through which the value of a variable can be determined. As can be seen from the above example, the var keyword is used to maintain the scope chain. If a variable is declared using the var keyword, it can be regarded as the end point of the scope chain. The definition of the formal parameters of the same function will also play a similar role.
Speaking of which, do you have a clearer understanding of this weird guy? According to its simple interpretation, this always points to the object that calls the function in which it is located. According to the scope and scope chain, we will clearly determine the true face of this. At the end, here is a simple variation of the example at the beginning:
function test(){
alert(this);
}
var obj=function(){
var name='testObj';
}
obj.objTest=test;
obj.objTest2=function(){
test();
}
test();
obj.objTest();
obj.objTest2();
What do you think it will prompt? You can try running it (:P);
Since this changes based on the change of the object that calls its function, can we forcefully change its calling object? The answer is yes. Future articles will introduce this part, as well as the implementation of different types of data members in Javascript, closures and other concepts.
Writing down some of my experiences and insights in the learning process is to share with everyone and also to examine my own shortcomings. If there are any problems with what I wrote, please criticize and give me advice. Thank you very much!

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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
