First of all, it must be said that the point of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In fact, this ultimately points to the object that called it (this There are some problems with this sentence, and I will explain why there is a problem later. Although most articles on the Internet say this, although in many cases there will be no problems in understanding it that way, in fact, it is inaccurate to understand it that way, so You will feel a little confused when you understand this), so I will explore this issue in depth next.
Why should we learn this? If you have studied functional programming or object-oriented programming, then you definitely know what it is used for. If you have not studied it, you don’t need to read this article for the time being. Of course, you can also read it if you are interested. After all, this is js. Something that must be mastered.
Example 1:
function a(){ var user = "追梦子"; console.log(this.user); //undefined console.log(this); //Window } a();
According to what we said above, this ultimately points to the object that calls it. The function a here is actually pointed out by the Window object. The following code can prove.
function a(){ var user = "追梦子"; console.log(this.user); //undefined console.log(this); //Window } window.a();
It’s the same as the above code. In fact, alert is also a property of window and is also clicked by window.
Example 2:
var o = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 } } o.fn();
This here points to object o. Because you call this fn through o.fn(), it naturally points to object o. I emphasize it again. One point, the point of this cannot be determined when the function is created. It can be determined when it is called. Whoever calls it will point to whom. Be sure to understand this.
In fact, Example 1 and Example 2 are not accurate enough. The following example can overturn the above theory.
If you want to fully understand this, you must look at the next few examples
Example 3:
var o = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 } } window.o.fn();
This code is almost the same as the code above , but why does this here not point to window? If according to the above theory, ultimately this points to the object that calls it. Here is an aside, window is a global object in js, and the variable we create is actually for window Add attributes, so you can use the window dot o object here.
Let’s not explain why this in the above code does not point to window. Let’s look at a piece of code.
var o = { a:10, b:{ a:12, fn:function(){ console.log(this.a); //12 } } } o.b.fn();
The object o is also pointed out here, but this also does not execute it. Then you will definitely say that what I said at the beginning is wrong? Actually it's not, it's just that what I said at the beginning was inaccurate. Next I will add a sentence. I believe you can completely understand the problem pointed by this.
Case 1: If there is this in a function, but it is not called by the upper-level object, then this points to window. What needs to be explained here is that in the strict version of js, this points to something other than window. window, but we will not discuss the strict version here. If you want to know more, you can search online.
Case 2: If there is this in a function, and this function is called by the upper-level object, then this points to the upper-level object.
Case 3: If there is this in a function, this function contains multiple objects. Although this function is called by the outermost object, this only points to the object above it. Example 3 can be proved. If you don’t believe it, then let’s continue to look at a few examples.
var o = { a:10, b:{ // a:12, fn:function(){ console.log(this.a); //undefined } } } o.b.fn();
Although there is no attribute a in object b, this this also points to object b, because this will only point to its upper-level object, regardless of whether there is anything this wants in this object.
There is another special situation, Example 4:
var o = { a:10, b:{ a:12, fn:function(){ console.log(this.a); //undefined console.log(this); //window } } } var j = o.b.fn; j();
Here this points to window. Are you confused? In fact, it is because you did not understand a sentence, which is also crucial.
This always points to the object that called it last, that is, who called it when it was executed. In Example 4, although function fn is referenced by object b, when fn is assigned to variable j is not executed, so it ultimately points to window. This is different from Example 3, which directly executes fn.
This is actually the same thing, but it will point to something different in different situations. There are some small mistakes in the above summary, which cannot be said to be errors, but The situation will be different under different circumstances, so I can't explain it all at once, I can only let you experience it slowly.
Constructor version of this:
function Fn(){ this.user = "追梦子"; } var a = new Fn(); console.log(a.user); //追梦子
这里之所以对象a可以点出函数Fn里面的user是因为new关键字可以改变this的指向,将这个this指向对象a,为什么我说a是对象,因为用了new关键字就是创建一个对象实例,理解这句话可以想想我们的例子3,我们这里用变量a创建了一个Fn的实例(相当于复制了一份Fn到对象a里面),此时仅仅只是创建,并没有执行,而调用这个函数Fn的是对象a,那么this指向的自然是对象a,那么为什么对象Fn中会有user,因为你已经复制了一份Fn函数到对象a中,用了new关键字就等同于复制了一份。
除了上面的这些以外,我们还可以自行改变this的指向,关于自行改变this的指向请看JavaScript中call,apply,bind方法的总结这篇文章,详细的说明了我们如何手动更改this的指向。
更新一个小问题当this碰到return时
function fn() { this.user = '追梦子'; return {}; } var a = new fn; console.log(a.user); //undefined
再看一个
function fn() { this.user = '追梦子'; return function(){}; } var a = new fn; console.log(a.user); //undefined
再来
function fn() { this.user = '追梦子'; return 1; } var a = new fn; console.log(a.user); //追梦子
function fn() { this.user = '追梦子'; return undefined; } var a = new fn; console.log(a.user); //追梦子
什么意思呢?
如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例。
function fn() { this.user = '追梦子'; return undefined; } var a = new fn; console.log(a); //fn {user: "追梦子"}
还有一点就是虽然null也是对象,但是在这里this还是指向那个函数的实例,因为null比较特殊。
function fn() { this.user = '追梦子'; return null; } var a = new fn; console.log(a.user); //追梦子
知识点补充:
1.在严格版中的默认的this不再是window,而是undefined。
2.new操作符会改变函数this的指向问题,虽然我们上面讲解过了,但是并没有深入的讨论这个问题,网上也很少说,所以在这里有必要说一下。
function fn(){ this.num = 1; } var a = new fn(); console.log(a.num); //1
为什么this会指向a?首先new关键字会创建一个空的对象,然后会自动调用一个函数apply方法,将this指向这个空对象,这样的话函数内部的this就会被这个空的对象替代。
以上就是JavaScript中this指针指向的彻底理解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

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.

Atom editor mac version download
The most popular open source editor