In daily study, we often encounter the usage of this. This article will explain it in detail.
You may have encountered this JS interview question:
var obj = { foo: function(){ console.log(this) } }var bar = obj.foo obj.foo() // 打印出的 this 是 objbar() // 打印出的 this 是 window
Please explain why the values of the functions in the last two lines are different.
——-
Beginners’ understanding of this has always been vague. Today’s article will explain it all once and for all.
And you can’t see this explanation anywhere else. Understand this article, all interview questions about this are just side dishes.
Function call
First of all, we need to start with the function call.
There are three function call forms in JS (ES5):
func(p1, p2) obj.child.method(p1, p2) func.call(context, p1, p2) // 先不讲 apply
Generally, beginners know the first two forms and think that the first two forms are "better" than the third form.
From reading this article, you must remember that the third calling form is the normal calling form:
func.call(context, p1, p2)
The other two are syntax sugar and can be equivalently changed into call form:
func(p1, p2) is equivalent to func.call(undefined, p1, p2)obj .child.method(p1, p2) is equivalent to obj.child.method.call(obj.child, p1, p2)
Please note it down. (We call this code "conversion code" for easy reference below)
So far our function call has only one form:
func.call(context, p1, p2)
In this way, this can explain
this, which is the context in the above code. It's that simple.
This is the context passed when you call a function. Since you never use the call form of function call, you never know it.
Let’s first look at how to determine this in func(p1, p2):
When you write the following code
function func(){ console.log(this)}func() 等价于 function func(){ console.log(this)}func.call(undefined) // 可以简写为 func.call()
Logically speaking, the printed this should be undefined, right? , but there is a rule in the browser:
If the context you pass is null or undefined, then the window object is the default context (the default context in strict mode is undefined)
So the above print result is window.
If you hope that this here is not window, it is very simple:
func.call(obj) // Then this inside is the obj object.
Look at obj again. How to determine this of child.method(p1, p2)
var obj = { foo: function(){ console.log(this) } } obj.foo()
According to "Conversion Code", we convert obj.foo() to
obj.foo.call(obj)
Okay, this is obj. Done.
Back to the topic:
var obj = { foo: function(){ console.log(this) } }var bar = obj.foo
obj.foo() // Convert to obj.foo.call(obj), this is objbar()// Convert to bar.call()/ / Since no context is passed// so this is undefined// Finally the browser gives you a default this - window object
[ ] Syntax
function fn (){ console.log(this) } var arr = [fn, fn2] arr0 // 这里面的 this 又是什么呢?
We can imagine arr0 is arr.0(). Although the syntax of the latter is wrong, the form corresponds to obj.child.method(p1, p2) in the conversion code, so you can convert happily:
arr0
Imagine it as arr.0()
and then convert it to arr.0.call(arr)
Then this inside is arr:)
Summary
this is the context passed in when you call a function.
If your function call form is not call form, please follow the "Conversion Code" to convert it to call form.
In the future, you will have no doubts about all written test questions related to this.
This article provides a related explanation of this. For more related content, please pay attention to the php Chinese website.
Related recommendations:
HTML5/CSS3 related knowledge explanation# Related examples of ##e
Summary of common APIs used by Javascript to operate DOM
The above is the detailed content of How to use this in Javascript. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
