Home  >  Article  >  Web Front-end  >  A detailed explanation of this, the basics of JavaScript

A detailed explanation of this, the basics of JavaScript

黄舟
黄舟Original
2017-06-04 10:23:201160browse

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.

df72941724e3b418c4483e6178863d77

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