Home Web Front-end JS Tutorial How to determine where this points in JavaScript

How to determine where this points in JavaScript

Sep 05, 2017 am 10:51 AM
javascript js this

It is said that JavaScript is a very flexible language. In fact, it can also be said that it is a confusing language. Let me share with you the knowledge of this in JavaScript through this article. Friends who are interested can take a look.

It is said that JavaScript is a very flexible language, but in fact it can also be said that it is a confusing language. It combines functional programming and object-oriented programming, coupled with the dynamic language feature, it is extremely powerful (in fact, it cannot be compared with C++, ^_^).

This

  • in JS is created inside the function

  • Points to the object bound to the function when called (a mouthful)

  • this cannot be assigned, but can be changed by call/apply

Directory

* A special case
* Start judging
* Rule 1: this in the object method points to the object itself (except in the form of arrow functions)
* Rule 2: This in a multi-layer nested function points to this which is equivalent to the most recent function containing this
* Rule 3: In the case of arrow functions and functions in non-object methods, this points to window
* Exercise Set
* This in an ordinary function
* After the function is executed, return this in another function (in an ordinary function)
* This in a multi-layer nested function (timer & Arrow function) 1
* This (timer & arrow function) in multi-layer nested functions 2

A special case

Before we officially start, let’s talk about a special case.


1

2

3

4

5

6

7

8

9

10

// 构造函数

function Student(name) {

 this.name = name

}

// 创建小明和小红两个实例

var XM = new Student('xiaoming')

var XH = new Student('xiaohong')

// 输出信息

console.log(XM) // Student {name: "xiaoming"}

console.log(XH) // Student {name: "xiaohong"}

Copy after login

In the constructor, the value on this will be bound to the newly created instance when the instance is created. It does not apply to the following judgment method, so it is hereby explained.

Start to judge

The following is a typical example, and our analysis starts from here.


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var x = {

 name: 'bw2',

 getName1: function() {

 console.log(this)

 },

 getName2: function() {

 setTimeout(() => {

  console.log(this)

 },0)

 },

 getName31: () => {

 console.log(this)

 },

 getName32: function() {

 return function() {

  console.log(this)

 }

 }

}

x.getName1() // {name: "bw2", getName1: ƒ}

x.getName2() // {name: "bw2", getName1: ƒ}

x.getName31() // Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

x.getName32()() // Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

Copy after login

Rule 1: this in the object method points to the object itself (except in the form of arrow functions)


1

2

3

4

5

6

7

var x = {

 name: 'bw2',

 getName1: function() {

 console.log(this)

 }

}

x.getName1() // {name: "bw2", getName1: ƒ}

Copy after login

Rule 2: This in a multi-level nested function points to this

which is equivalent to the latest function containing this. The arrow function does not have an independent this scope, so continue to the outer layer and reach getName: function( ){}. Then it's him. This pointer is equivalent to the this pointer inside this function. According to Rule 1, this points to the object itself.


1

2

3

4

5

6

7

8

9

10

var x = {

 name: 'bw2',

 getName2: function() {

 console.log(this) // 等同于此处的this

 setTimeout(() => {

  console.log(this) // 原始的this位置

 },0)

 }

}

x.getName2() // {name: 'bw2', getName1: ƒ}

Copy after login

We can try running it in the browser and see the results.

Rule 3: In the case of arrow functions and functions in non-object-pointing methods, this points to window

According to rule 2, this points to the nearest function, so this here is equivalent to return This in the function is not this in the object method, so it points to the global.

Does it feel a little strange? But practice has proven this to be the case.


1

2

3

4

5

6

7

8

9

10

11

12

13

var x = {

 name: 'bw2',

 getName31: () => {

 console.log(this)

 },

 getName32: function() {

 return function() {

  console.log(this)

 }

 }

}

x.getName31() // Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

x.getName32()() // Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

Copy after login

Exercise Set

We welcome everyone to judge according to rules one to three, guess the results, and Test in browser. You can also reply with the test results and discuss them together.

Due to my limited ability, this series of rules may fail in some cases. Everyone is welcome to discuss together.

The following is the time to do the questions.

This in an ordinary function


1

2

3

4

function x() {

 console.log(this)

}

x()

Copy after login

After the function is executed, it returns this in another function (in an ordinary function)


1

2

3

4

5

6

function xx(){

 return function() {

 console.log(this)

 }

}

xx()()

Copy after login

This (timer & arrow function) in multi-level nested functions 1


1

2

3

4

5

6

7

8

9

var x = {

 name: 'bw2',

 getName: () => {

 setTimeout(() => {

  console.log(this)

 },0)

 }

}

x.getName()

Copy after login

Multi-level nesting This in the function (timer & arrow function) 2


1

2

3

4

5

6

7

8

9

var x = {

 name: 'bw2',

 getName: () => {

 setTimeout(function() {

  console.log(this)

 },0)

 }

}

x.getName()

Copy after login

Again, this rule is experimental and has not been tested on a large scale. It is not guaranteed to work in all situations. There are consistent results below. If you find a situation where the rule judgment fails, please leave a message and discuss it together.

The above is the detailed content of How to determine where this points in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

See all articles