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]);
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!

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

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.

Dreamweaver Mac version
Visual web development tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools