Home  >  Article  >  Web Front-end  >  Detailed answer to this in JavaScript (graphic tutorial)

Detailed answer to this in JavaScript (graphic tutorial)

亚连
亚连Original
2018-05-19 10:45:361206browse

The this object of a function in JavaScript is the scope in which the function is executed (for example: when a function is called in the global scope of a web page, the this object refers to window).

This in JavaScript is very different from this in object-oriented languages ​​such as Java. The bind(), call() and apply() functions further extend the flexibility of this.

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 Shift J) (Mac: Cmd Option J) and enter:

console.log(this);

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';
We can control Enter myName to access its value:

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

When the this keyword is used inside a declared object, its value will be bound to the nearest function that calls this. parent object. 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 keyword

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 object of this in call(), bind(), and apply(). 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 to store the parameters of the add function.

The bind() function is similar to call(), but the bind() function will not be called immediately. The bind() function returns a function and binds this. Next, let’s use examples to help understand the application scenarios of the bind() function:

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

Execution:

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

What if we want to use the value of large.a instead of small.a? We can use call/apply:

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

But what should we do if we don’t know what values ​​​​should be passed in these three parameters yet? We can use bind:

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

If we print bindTest in the console, we will See:

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

Note: This function has bound this to the large object and passed in the first parameter b. Therefore, we next need to pass in the remaining parameters:

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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

related articles:

The pointing of this in JS and the functions of call and apply (picture and text tutorial)

this# in JS The pointing of ## and the role of call and apply_Basic knowledge

The difference between self, static, $this in PHP and the detailed explanation of late static binding

The above is the detailed content of Detailed answer to this in JavaScript (graphic tutorial). 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