search
HomeWeb Front-endJS TutorialA detailed explanation of this, the basics of JavaScript

This object of function in JavaScript is the scope in which the function is executed (for example: when calling the function in the global scope of the web page When, this object

refers to

is window). This in JavaScript is very different from this in languages ​​such as JavaObject-oriented. The bind(), c

all

() and apply() functions even use this The flexibility is further extended.

In order to ensure readability, this article uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, and the translation is for learning only.

If you don’t understand the JavaScript keyword this deeply enough, you may sometimes fall into unexpected pits. Here we have summarized 5 general rules to help you determine what this actually points to. Although not all situations are covered, most everyday situations can be correctly inferred using these rules.

The value of this is usually determined by the execution environment of the function, which means it depends on how the function is called;

Every time the same function is called, this may point to a different object;Global Object
)

Open the Chrome browser developer panel (Windows: Ctrl + Sh

if

t + J) (Mac: Cmd + Option + J), and enter:

console.log(this);

to see what is output?

// Window {}

window object

! Because in the global scope, this points to the global object. The global object in the browser is the window object.

In order to give you a clearer understanding of why this points to the window object, let's look at another example:

var myName = 'Brandon';
myName
// 输出 'Brandon'
In fact, all

variables defined globally

are bound to the window object . Let's do the following test:

window.myName
// 输出 'Brandon'
window.myName === myName
// 输出 true

Now let's put this inside the function and see what the effect is.

function test(){
 return this;
}
test();

You will find that this still points to the global window object. Because the this keyword is not inside a declared object, it defaults to the global window object. This may be a bit difficult for most beginners to understand. After reading this article, you will suddenly understand.

Note: If in strcit mode, this is undefined in the above example. Declared Object (
Declare
d Object)

When the this keyword is used inside a declared object, its value will be Binds to the nearest parent object of the function that called this. Let's use an example to illustrate this problem:

var person = {
 first: 'John',
 last: 'Smith', 
 full: function() {
  console.log(this.first + ' ' + this.last);
 }
};
person.full();
// 输出 'John Smith'

If this is used in the full function of the declared object person, then the nearest parent object of the full function that calls this is person, so this points to person.

In order to better describe that this actually points to the person object, you can copy the following code to the browser console and print this out.

var person = {
 first: 'John',
 last: 'Smith', 
 full: function() {
  console.log(this);
 }
};
person.full();
// 输出 Object {first: "John", last: "Smith", full: function}

Let’s look at a more complex example next:

var person = {
 first: 'John',
 last: 'Smith',
 full: function() {
  console.log(this.first + ' ' + this.last);
 },
 personTwo: {
  first: 'Allison',
  last: 'Jones',
  full: function() {
   console.log(this.first + ' ' + this.last);
  }
 }
};

Here we have nested objects. At this time, who does this point to? Let's print it out and take a look:

person.full();
// 输出 'John Smith'
person.personTwo.full();
// 输出 'Allison Jones'

You will find that the rules we described earlier are met: its value will be bound to the nearest parent object of the function that calls this. new
Keywords

When using the new keyword to construct a new object, this will be bound to the new object. Let's look at an example:

function Car(make, model) {
 this.make = make;
 this.model = model;
};

Based on the first rule, you might infer that this points to the global object. But if we use the new keyword to declare a new variable, this in the Car function will be bound to a new empty object, and then the values ​​of this.make and this.model will be initialized.

var myCar = new Car('Ford', 'Escape');
console.log(myCar);
// 输出 Car {make: "Ford", model: "Escape"}

call, bind, and apply

We can explicitly set the binding of this in call(), bind(), and apply() object. These three functions are very similar, but we need to pay attention to their subtle differences.

Let's look at an example:

function add(c, d) {
 console.log(this.a + this.b + c + d);
}
add(3,4);
// 输出 NaN

add function outputs NaN because this.a and this.b are not defined.

Now we introduce the object and use call() and apply() to call:

function add(c, d) {
 console.log(this.a + this.b + c + d);
}
var ten = {a: 1, b: 2};
add.call(ten, 3, 4);
// 输出 10
add.apply(ten, [3,4]);
// 输出 10
When we use add.call(), the first parameter is the object that this needs to be bound to , the rest are the original parameters of the add function. Therefore, this.a points to ten.a, and this.b points to ten.b. add.apply() is similar, except that the second parameter is an array used to store the parameters

of the add###function. ###

bind()函数和call()类似,但是bind()函数不会立即被调用。bind()函数会返回一个函数,并且将this绑定好。接下来我们来用例子来帮助理解bind()函数的应用场景:

var small = {
 a: 1,
 go: function(b,c,d){
  console.log(this.a+b+c+d);
 }
}
var large = {
 a: 100
}

执行:

small.go(2, 3, 4);
// 输出 10

如果我们想使用large.a的值,而不是small.a呢? 我们可以使用call/apply:

small.go.call(large, 2, 3, 4);
// 输出 109

但是,如果我们现在还不知道这三个参数应该传入什么值,应该怎么办呢? 我们可以使用bind:

var bindTest = small.go.bind(large, 2);

如果我们将bindTest在控制台下打印出来,我们会看到:

console.log(bindTest);
// 输出 function (b,c,d){console.log(this.a+b+c+d);}

注意:该函数已经将this绑定到large对象,并且传入了第一个参数b。所以,我们接下来是需要传入余下的参数即可:

bindTest(3, 4);
// 输出 109

箭头函数(=>)

因为需要很大的篇幅,我们会专门写一篇博客来介绍。

结论

当你读完这篇博客,你应该可以理解大多数情况下this指向的对象。
接下来我们来总结一下:

this的值通常是由当前函数的执行环境所决定;
在全局作用域,this指向全局对象 (window对象);
当使用new关键字声明,this指向新建对象;
我们可以使用call(), bind(), apply()来设置this;
箭头函数不会绑定this。

The above is the detailed content of A detailed explanation of this, the basics of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

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

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools