In view of the way this coquettish operation, the understanding of this is a timeless topic, this article attempts to nail it by breaking it into six pieces Stay with this annoying monster.
First of all
this is all about context.
To put it bluntly, this is to find the boss and the object (context object) that owns the current context (context).
Big bosses can be divided into six levels. The higher the level, the greater the power. This will only recognize the largest one.
The first level: the end of the world
The boss with the least power is a spare tire. Under normal circumstances, it is the global situation, and in the browser, it is the window; in the case of use strict, it is undefined.
function showThis () { console.log(this) } function showStrictThis () { 'use strict' console.log(this) } showThis() // window showStrictThis() // undefined
The second level: turning stone into gold
The boss of the second level puts it bluntly and is to find the dot in front of this function.
If the function that uses this belongs to a context object, then this context object is bound to this.
For example, in the following example, boss is the context object of returnThis, or returnThis belongs to boss.
var boss = { name: 'boss', returnThis () { return this } } boss.returnThis() === boss // true
Be careful with the following example. Can you come up with the answer?
var boss1 = { name: 'boss1', returnThis () { return this } } var boss2 = { name: 'boss2', returnThis () { return boss1.returnThis() } } var boss3 = { name: 'boss3', returnThis () { var returnThis = boss1.returnThis return returnThis() } } boss1.returnThis() // boss1 boss2.returnThis() // ? boss3.returnThis() // ?
The answer is boss1 and window Oh, did you guess it right?
Just look at the function that uses this.
In boss2.returnThis, the function that uses this is boss1.returnThis, so this is bound to boss1;
In boss3.returnThis, the function that uses this is returnThis, so this is bound to Order a spare tire.
How to bind this to boss2?
var boss1 = { name: 'boss1', returnThis () { return this } } var boss2 = { name: 'boss2', returnThis: boss1.returnThis } boss2.returnThis() //boss2
Yes, as long as the function using this belongs to boss2.
Third level: fingertips for marriage
The bosses of the third level are Object.prototype.call and Object.prototype.apply, which can specify this through parameters. (Note that this cannot be directly assigned, this = 2 will report a ReferenceError.)
function returnThis () { return this } var boss1 = { name: 'boss1' } returnThis() // window returnThis.call(boss1) // boss1 returnThis.apply(boss1) // boss1
Fourth level: Each other
The boss of the fourth level is Object.prototype.bind, he Not only does it provide permanent binding through a new function, it also overrides the commands of the third-level boss.
function returnThis () { return this } var boss1 = { name: 'boss1'} var boss1returnThis = returnThis.bind(boss1) boss1returnThis() // boss1 var boss2 = { name: 'boss2' } boss1returnThis.call(boss2) // still boss1
The fifth layer: There is a universe inside
A place that is easier to ignore and bind this is new. When we new a function, this will be automatically bound to the new object, and then the function will be called. It overrides bind 's binding.
function showThis () { console.log(this) } showThis() // window new showThis() // showThis var boss1 = { name: 'boss1' } showThis.call(boss1) // boss1 new showThis.call(boss1) // TypeError var boss1showThis = showThis.bind(boss1) boss1showThis() // boss1 new boss1showThis() // showThis
The sixth level: mountains of military orders
The last powerful boss is the arrow function of ES2015. This in arrow functions is no longer glamorous. It is permanently sealed into the current lexical scope. It is called Lexical this and can be determined before the code is run. No other big guy can cover it.
The advantage of this is that it is convenient to use the current scope of this of the callback function without fear of causing confusion.
So for the arrow function, just look at where it is created.
If you are interested in the lexical scope implemented by V8, you can take a look here.
function callback (cb) { cb() } callback(() => { console.log(this) }) // window var boss1 = { name: 'boss1', callback: callback, callback2 () { callback(() => { console.log(this) }) } } boss1.callback(() => { console.log(this) }) // still window boss1.callback2(() => { console.log(this) }) // boss1
You need to pay attention to the following weird usage:
var returnThis = () => this returnThis() // window new returnThis() // TypeError var boss1 = { name: 'boss1', returnThis () { var func = () => this return func() } } returnThis.call(boss1) // still window var boss1returnThis = returnThis.bind(boss1) boss1returnThis() // still window boss1.returnThis() // boss1 var boss2 = { name: 'boss2', returnThis: boss1.returnThis } boss2.returnThis() // boss2
If you don’t know why it is boss2 in the end, continue to understand "For arrow functions, just look at where it is created" sentence.
The above is the content of the six hurdles of JavaScript This. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

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.