


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!

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


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

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
