One article to understand the this pointing problem in JavaScript
This article brings you relevant knowledge about JavaScript, which mainly introduces the related issues pointed by this. This means "this, current" and is a pointer variable. It dynamically points to the running environment of the current function. Let's take a look at it. I hope it will be helpful to everyone.
【Related recommendations: JavaScript video tutorial, web front-end】
The concept of this:
In js, this means "this; current", is a pointer variable, which dynamically points to the running environment of the current function.
When the same function is called in different scenarios, the pointer of this may also change, but it will always point to the real caller of the function in which it is located; if there is no caller , it points to the global object window.
Ordinary function: Regarding this, whoever calls it points to whoever calls it. If there is no caller, it points to the global object window.
Arrow function: This of the arrow function points to the object used in the function scope.
1. This in the global environment points to
In the global scope, this always points to the global object window, regardless of whether it is in strict mode or not!
##congsole.log()The complete writing method is
window.console.log(), window can be omitted ,
window called the console.log() method, so this points to window at this time.
2. This within the function
- This within the ordinary function is divided into two situations, strict mode and non-strict mode.
1. In strict mode:
window.test()Call function this points to window. Therefore, in
strict mode, when we call the code, we must strictly write the object of the called function, and no omissions or abbreviations are allowed.
2. In non-strict mode:
window.test()When calling function objects, this points to window.
3. This in the object
This in the internal methods of the object points to the object that calls these methods, that is, Whoever calls it points to .
1. One-level object:
obj.skill() method, The return value is
Mengya, indicating that this points to obj at this time.
2. Second-layer object:
obj.obj2.skill2 (), the return value is
Luban, indicating that this in the skill2() method points to obj2.
Summary:
- The definition position of a function does not affect its this pointer,
this pointer is only related to the object that calls the function.
- For multi-level nested objects,
the this of the internal method points to the object closest to the called function.
4. This
Arrow function: this Points to the object used in the function scope.
- Important features of the arrow function
- :
There is no this and arguments in the arrow function, there really is none!
The arrow function does not have its own this pointer, it will capture the outer execution environment - of its
definition, and inherit it This this value, points to the object where it is currently defined. The this point of the arrow function is determined when it is defined, and will never change thereafter. Even if you use call(), apply()
,
bind()and other methods to change this pointer, it is not possible.
Example 1:
- # declares the global variable Obj, and this points to the global function where the arrow function is located The object of the domain, that is, the window object.
Example 2:
Since the show function is an arrow function, it cannot be bound to itself Define this, so find its upper-level scope. If the parent scope is still an arrow function, look up again, layer by layer, until you reach the point of this.
window.show()
The return value is window, so this points to window at this time;window.obj.show(), obj
is an object, not an arrow function, so it stops when it finds this point, and this is bound to obj. window calls obj, so this in obj also points to window.
5. This in the constructor
This in the constructor points to Example.
As can be seen from the above figure, this in the constructor points to the instance created under the constructor.
Six, this value in the prototype chain
this value is in an inheritance mechanism, still It points to the object it originally belongs to, not the object it belongs to when it is found on the prototype chain.
7. Methods to change the point of this
1. call()
-
call(a, b, c)
method receives three parameters, the first one is pointed to by this, the second one, and the three are the actual parameters passed to the function , which can be any data type such as numbers, strings, arrays, etc.
Example:
//定义函数function fn(n1,n2){ console.log(this); console.log(n1,n2)}//调用call()方法fn.call();//=>this:window;let obj = {fn:fn};fn.call(obj); //=>this:obj;n1,n2:undefinedfn.call(1,2);//=>this: 1;n1=2,n2=undefined;fn.call(obj,1,2);//=>this: obj;n1=1,n2=2; //Call方法的几个特殊属性 //非严格模式下fn.call(undefined);//this=>windowfn.call(null);//this=>window //严格模式下"use strict"fn.call(undefined);//this=>undefinedfn.call(null);//this=>null
2. apply()
apply(a, [b])
is basically the same as call. The only difference is the parameter passing method. apply puts the parameters that need to be passed tofn()
into an array. (or array-like), although it is written as an array, it is equivalent to passing it tofn()
one by one.//call()的传参方式 fn.call(obj, 1, 2);//apply()的传参方式fn.apply(obj, [1, 2]);
Copy after login
Example:
//apply方法的使用和call方法基本相同,唯一的区别是,apply方法传参要求是数组类型的,数组内可以任意形式的数据 function fn (n1,n2){ console.log(this); console.log(n1,n2) console.log(arguments)}let obj = {fn:fn}; //调用apply()方法 fn.applay(abj,[1,2]);fn.applay(abj,1,2); //报错 fn.applay(abj,[11,'apply',{a:123}]); //注意第二个参数必须是数组,否则会报错
3. bind()
bind (a, b, c)
: The syntax is exactly the same as call. The difference is whether to execute immediately or wait for execution. bind is not compatible with IE6~8-
The only difference between bind and call is that call directly changes the direction of function test, while bindgenerates a new function test2()
, this function changes the pointer.
//call()方法:改变fn中的this,并且把fn立即执行fn.call(obj, 1, 2); //bind()方法:改变fn中的this,fn并不执行fn.bind(obj, 1, 2);
Example:
//bind和call方法调用形式类似,但是原理完全不同 fn.call(obj,10,20);//=>fn先执行,将fn内的this指向obj,并且把参数10,20传递给fn fn.bind(obj,10,20)//bind是先将fn中的this指向obj,并且将参数10,20预先传递给fn,但是此时的fn并没有被执行,只有fn执行时this指向和传递参数才有作用 fn.bind(obj,10,20);//=>不会有任何输出 fn.bind(obj,10,20)();//=>调用后才会有输出 //=>需求:点击box这个盒子的时候,需要执行fn,并且让fn中的this指向obj oBox.onclick=fn; //=>点击的时候执行了fn,但此时fn中的this是oBox oBox.onclick=fn.call(opp); //=>绑定事件的时候就已经把fn立即执行了(call本身就是立即执行函数),然后把fn执行的返回值绑定给事件 oBox.onclick=fn.bind(opp); //=>fn.bind(opp):fn调取Function.prototype上的bind方法,执行这个/* * function(){ * fn.call(opp); * } */ oBox.onclick=function(){ //=>this:oBox fn.call(opp); }
[Related recommendations:Same points:
call, apply and bind are all public internal methods of JS functions. They all reset the this of the function and change the execution of the function.
Difference:
bind creates a new function, while call and aplay are used to call functions;
- call and apply have the same function, except that the parameters provided by call for the function are listed one by one, while the parameters provided by apply for the function are an array
JavaScript video tutorial、webfrontend】
The above is the detailed content of One article to understand the this pointing problem in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
