A detailed explanation of this in JavaScript
This in JavaScript is relatively flexible. This may be different depending on different environments or when the same function is called in different ways. But there is a general principle, That is, this refers to the object that calls the function.
Series Catalog
Introduction to JavaScript’s Closure (Closure)
-
Introduction to JavaScript’s this
In-depth introduction to the prototype chain and inheritance of JavaScript
The following are my study notes, which are listed into 8 situations.
Global this (browser)
This in the global scope generally points to the global object. In the browser, this object is window. In node, this object is global.
console.log(this.document === document); // true (document === window.document) console.log(this === window); // true this.a = 37; //相当于创建了一个全局变量a console.log(window.a); // 37
This of general functions (browser)
For general function declarations or function expressions, if the function is called directly, this still points to the global object. In the browser, this object is window. In node, this object is global.
function f1(){ return this; } f1() === window; // true, global object
Give another example, it will be very clear after reading it
function test(){ this.x = 1; alert(this.x); } test(); // 1
In order to prove that this is the global object, make some changes to the code:
var x = 1; function test(){ alert(this.x); } test(); // 1
The running result is still 1. Change it again:
var x = 1; function test(){ this.x = 0; } test(); alert(x); //0
But in strict mode, when a function is called, this points to undefined. This is one reason why node uses strict mode.
function f2(){ "use strict"; // see strict mode return this; } f2() === undefined; // true
This as a function of an object method
It is more common to use this as an object method.
In the following example, we create an object literal o. There is an attribute f in o, and its value is a function object. We often call the function as the value of the object attribute. method. When called as a method of an object, this points to the object o
var o = { prop: 37, f: function() { return this.prop; } }; console.log(o.f()); // logs 37
We do not necessarily have to define an object like a function literal. In the following case, we only define an object o. If If the independent() function is called directly, this will point to window, but when we temporarily create a property f through assignment and point it to the function object, we still get 37.
var o = {prop: 37}; function independent() { return this.prop; } o.f = independent; console.log(o.f()); // logs 37
So it doesn’t depend on how the function is created, but as long as the function is called as a method of the object, this will point to the object.
This on the object prototype chain
In the following example: we first create an object o, which has an attribute f and a function As the value of the object attribute, we create an object p through Object.create(o), p is an empty object, and its prototype will point to o, and then use p.a = 1; p.b = 4 to create the attributes on the object p, then When we call the method on the prototype, this.a, this.b can still get a and b on the object p. What needs to be noted here is that the prototype of p is o. When we call p.f(), we call the attribute f on the prototype chain o. This on the prototype chain can get the current object p.
var o = {f:function(){ return this.a + this.b; }}; var p = Object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5
get/set method and this
This in the get/set method will generally point to the object in the get/set method
function modulus(){ return Math.sqrt(this.re * this.re + this.im * this.im); } var o = { re: 1, im: -1, get phase(){ return Math.atan2(this.im, this.re); } }; Object.defineProperty(o, 'modulus', { //临时动态给o对象创建modules属性 get: modulus, enumerable:true, configurable:true}); console.log(o.phase, o.modulus); // logs -0.78 1.4142
In the constructor this
If you use new to call MyClass as a constructor, this will point to an empty object, and the prototype of this object will point to MyClass.prototype (see this article for a summary of the prototype chain), but the call At that time, the assignment of this.a = 37 was made, so in the end this will be used as the return value (if no return statement is written, or if the return is a basic type, this will be used as the return value). In the second example, the return statement returns the object, Then a = 38 will be used as the return value
function MyClass(){ this.a = 37; } var o = new MyClass(); console.log(o.a); // 37 function C2(){ this.a = 37; return {a : 38}; } o = new C2(); console.log(o.a); // 38
The call/apply method and this
In addition to different calling methods, some methods of the function object can modify the this of the function execution, such as call/ apply.
There is basically no difference between call and apply, except that call passes parameters in a flat way, while apply passes an array in. As in the following example
When should we use call and apply? For example, if we want to call Object.prototype.toString, but we want to specify a certain this, then we can use Object.prototype.toString.call(this) to call some methods that cannot be called directly. Take the following example:
function add(c, d){ return this.a + this.b + c + d; } var o = {a:1, b:3}; add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 //第一个参数接收的是你想作为this的对象 add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // "[object Number]"
bind method and this
bind method is provided starting from es5, so ie9+ only supports
function f(){ return this.a; } var g = f.bind({a : "test"}); //想把某个对象作为this的时候,就把它传进去,得到一个新对象g console.log(g()); // test //重复调用的时候,this已经指向bind参数。这对于我们绑定一次需要重复调用依然实现绑定的话,会比apply和call更加高效(看下面这个例子) var o = {a : 37, f : f, g : g}; console.log(o.f(), o.g()); // 37, test //o.f()通过对象的属性调用,this指向对象o;比较特殊的是即使我们把新绑定的方法作为对象的属性调用,o.g()依然会按之前的绑定去走,所以答案是test不是g
Summary
Doing projects Only then did I realize how important these basic concepts are. If you don’t implement them one by one, you will really fall into a pit accidentally. In the future, I will also summarize the prototype chain, scope, inheritance, chain call, regularity and other knowledge. Welcome to pay attention to
. The above is the detailed explanation of this in JavaScript. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!

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

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

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

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.

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

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

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

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
