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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools