


Detailed test explanation of the problem pointed by this keyword in Javascript
This is a feature in Javascript that is very easy to misunderstand and then use incorrectly. Therefore, the following article mainly introduces to you the relevant information about the problem of this keyword pointing in Javascript. The test questions in the article test your familiarity with this. Friends in need can refer to it. Let's take a look together.
Preface
Javascript is an object-based dynamic language, that is to say, everything is an object. A typical example is that functions are also treated as ordinary objects. Javascript can implement object-oriented programming through certain design patterns, in which this "pointer" is a very important feature in realizing object-oriented programming. This article will give you a detailed introduction to the relevant content pointed to by the this keyword in Javascript. Let us do a small test first. If you get all the answers correct, congratulations, you don’t need to read any further.
Test questions
First question
<script> var str = 'zhangsan'; function demo() { var str = 'lisi'; alert(this.str); } window.demo(); // ?? var obj = { str: "wangwu", say: function() { alert(this.str); } } obj.say(); // ?? var fun = obj.say; window.fun(); // ?? </script>
Second question
<script> var username = 'zhangsan'; (function() { var username = 'lisi'; alert(this.username); // ?? })() function demo() { var username = 'wangwu'; function test() { alert(this.username); } test(); // ?? } demo(); </script>
Third question
<script> function Person() { this.username = 'zhangsan'; this.say = function() { alert('我叫' + this.username); } } var p = new Person(); p.say(); // ?? var p1 = new Person(); p1.say(); // ?? </script>
Question 4
##
<script> var username = 'zhangsan'; function demo() { alert(this.username) } var obj1 = { username: "lisi" }; var obj2 = { username: "wangwu" }; demo(); // ?? demo(obj1); // ?? demo(obj2); // ?? demo.call(obj1); // ?? demo.apply(obj2); // ?? </script>
Answer
- The first question: zhangsan wangwu zhangsan
- The second question: zhangsan zhangsan
- The third question: My name is zhangsan My name is zhangsan
- The fourth question: zhangsan zhangsan zhangsan lisi wangwu
this
- points to the calling function Object
- No object calling function/Anonymous function self-calling (this points to window)
- Object generated through new
- apply/call
#1. Point to the object of the calling function
<script> // this:指向调用函数的对象 var str = 'zhangsan'; function demo() { var str = 'lisi'; //this->window console.log(this); alert(this.str); } window.demo(); // zhangsan var obj = { str: "wangwu", say: function() { // this->obj alert(this.str); } } obj.say(); // wangwu var fun = obj.say; window.fun(); // zhangsan </script>
- The global function (demo) belongs to the method of the window object. The window calls demo, so this points to the window
- obj calls the say method, and this Pointing to obj
- fun() is a global function, and the declared fun receives a simple function in obj and does not call it (obj.say() is the function that is called ), fun at this time is a function (function(){alert(this.str);}), then when fun() calls the function, this points to window
- Who calls the function, then this points to who
<script> // 2.匿名函数自执行|匿名函数|无主函数 this->window var username = 'zhangsan'; // 匿名函数自执行 this->window (function() { var username = 'lisi'; console.log(this); // window alert(this.username); // zhangsan })() function demo() { var username = 'wangwu'; // 无主函数 this->window function test() { // this->window alert(this.username); } test(); // zhangsan } demo(); </script>
- Because the anonymous function has no name, it is attached to window
- test(), Whoever calls test points to who. Of course, after experimenting, it is not called by window, nor is it called by demo. If no one cares about it, then it points to window. It is equivalent to a mainless function that has no owner calling it.
<script> // 3.通过new的对象:this指向产生的对象 // 函数 function Person() { // 属性 this.username = 'zhangsan'; // 方法 this.say = function() { // this->p console.log(this); // Person对象 alert('我叫' + this.username); } } // 实例化出一个对象:p就具有了username属性和say方法 var p = new Person(); console.log(p); // Person对象 console.log(p.username); // zhangsan p.say(); // 我叫zhangsan // this->p1 var p1 = new Person(); p1.say(); // Person对象 我叫zhangsan </script>
- 4. Apply/call call
First of all, let’s understand what apply()/call() is?
function.call([thisObj[,arg1[, arg2[, [,.argN]]]]]) function.apply([thisObj[,argArray]])
1. Call the function function, but this in the function points to thisObj (change the internal pointer of the object)
2. If thisObj is not passed parameter, the default is the global object
3. Contact and difference between call()/apply()
Contact: The function is the same, the first parameter is thisObj
Difference: If there are more parameters passed
The actual parameters of call() are listed one by one
The actual parameters of apply() The parameters are all placed in the second array parameter
An example of understanding apply()/call():
<script> // apply()/call() function demo() { console.log(123); } // 调用函数的时候,demo.call()/demo.apply()最终调用的还是demo() demo(); // 123 demo.call(); //123 demo.apply(); // 123 </script> <script> // call()/apply()的区别: // call()参数单独再call中罗列 // apply()的参数通过数组表示 function demo(m, n, a, b) { alert(m + n + a + b); } demo(1, 5, 3, 4); // 13 demo.call(null, 1, 5, 3, 4); // 13 demo.apply(null, [1, 5, 3, 4]); // 13 </script>
The fourth usage example of this
<script> // this的第四个用法:call(obj)/apply(obj):强制性的将this指向了obj var username = 'zhangsan'; function demo() { alert(this.username) } var obj1 = { username: "lisi" }; var obj2 = { username: "wangwu" }; // call()/apply():打劫式的改变了this的指向 demo(); // zhangsan demo(obj1); //zhangsan demo(obj2); //zhangsan demo.call(obj1); // lisi demo.apply(obj2); // wangwu </script>
- Whether you use call or apply, the demo function will eventually be called, but they will force this to point to obj1/obj2, and force this to point to their first parameter object.
The above is the detailed content of Detailed test explanation of the problem pointed by this keyword in Javascript. For more information, please follow other related articles on the PHP Chinese website!

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.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

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

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.

Atom editor mac version download
The most popular open source editor