The principle and direction of JavaScript this

The principle and direction of JavaScript this

How to determine what this points to?

  • ①When called in the global environment, it points to window.
  • ② As a method call on an object, it points to that object.
  • ③As a constructor call, it points to the newly created object.
  • ④You can use apply, call, and bind to change the direction of this.
  • ⑤The this in the arrow function is bound to the context in which it is defined and cannot be changed. The this of the arrow function points to the this of the first non-arrow function closest to it found in the outer layer.

How to understand the this principle?

To learn JavaScript, you need to understand the following two ways of writing:

var obj = {
  foo: function () {}
};
 
var foo = obj.foo;
 
//Writing method 1 obj.foo()
 
//Writing method 2 foo()

These two ways of writing are one function call and one object method. Although obj.foo and foo both point to a function, their execution results may be different. Take a look at the following code:

var obj = {
  foo: function () { console.log(this.bar) },
  bar: 1
};
 
var foo = obj.foo;
var bar = 2;
 
obj.foo() // 1
foo() // 2

Why are the running results different? Because the function body uses the this keyword, many textbooks and materials will tell you that this refers to the environment in which the function is running. For obj.foo(), foo runs in the obj environment, so this points to obj; for foo(), foo runs in the global environment, so this points to the global environment. Therefore, the operating results of the two are different.

So how do you determine where this points to? Or in which environment does this run?

var obj = { foo: 5 };

The above code assigns an object to the variable obj. The JavaScript engine will first generate an object {foo: 5} in the memory, and then assign the address of this object to obj.

obj is a variable address. Reading obj.foo will first get the memory address from obj, then read the original object from this address and return the foo attribute.

How is the foo property stored in memory?

{
  foo: {
    [[value]]: 5
    [[writable]]: true
    [[enumerable]]: true
    [[configurable]]: true
  }
}

The value of the foo attribute is stored in the value attribute of the attribute description object.

What if the value of the property is a function?

var obj = { foo: function () {} };

At this time, the JavaScript engine will save the function separately in the memory, and then assign the address of the function to the value attribute of the foo attribute.

{
  foo: {
    [[value]]: The address of the function...
  }
}

Because a function is stored separately in memory, it can be executed in different environments (contexts).

var f = function () {};
var obj = { f: f };
 
// Execute f() alone
 
// obj environment executes obj.f()

JavaScript allows you to reference other variables in the current environment within a function body.

var f = function () {
  console.log(x);
};

This function uses other variables X.

Look at the code below

var f = function () {
  console.log(this.x);
}
 
var x = 1;
var obj = {
  f: f,
  x: 2,
};
 
// Execute f() alone // 1
 
// obj environment executes obj.f() // 2

You can see that the results of function execution are different. Function f is executed globally, so what about its this? this.x refers to the global environment's x.

As for obj.f executed in the obj environment, its this is obviously in the obj environment, so this points to obj.x in the obj environment.

So, at the beginning of the article, obj.foo() finds foo through obj, so it is executed in the obj environment. Once var foo = obj.foo, the variable foo directly points to the function itself, and the function itself foo() is in the global environment, so foo() is executed in the global environment.

function foo() {
    console.log(this.name);
}
 
function Foo(fn) {
    fn();
}
 
var obj = {
    name: 'zl',
    foo,
}
 
var name = "Heternally";
Foo(obj.foo);

So what is the result of executing the above code?

This is the end of this article about the principle and detailed explanation of JavaScript this. For more relevant JavaScript this content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of this pointing in JS arrow function
  • Why is there this in JS?
  • Detailed explanation of this reference and custom properties in JavaScript
  • Detailed explanation of the this pointing problem in JavaScript
  • Detailed explanation of function classification and examples of this pointing in Javascript
  • Detailed explanation of this pointing problem in JavaScript function
  • Detailed explanation of this pointing problem in JavaScript
  • JavaScript in-depth analysis of the direction of this and how to modify the direction

<<:  It's the end of the year, is your MySQL password safe?

>>:  Overview of the basic components of HTML web pages

Recommend

Using JS to determine the existence of elements in an array in ten minutes

Preface In front-end development, you often need ...

Web page printing thin line table + page printing ultimate strategy

When I was printing for a client recently, he aske...

Example code for Html layered box-shadow effect

First, let’s take a look at the picture: Today we...

Mysql keeps the existing content and adds content later

This command modifies the data table ff_vod and a...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

Detailed explanation of Nginx http resource request limit (three methods)

Prerequisite: nginx needs to have the ngx_http_li...

CSS Tutorial: CSS Attribute Media Type

One of the most important features of a style she...

Vue uses Canvas to generate random sized and non-overlapping circles

Table of contents Canvas related documents Effect...

How to maintain MySQL indexes and data tables

Table of contents Find and fix table conflicts Up...

Detailed explanation of the difference between $router and $route in Vue

We usually use routing in vue projects, and vue-r...

MySQL 5.7.18 Green Edition Download and Installation Tutorial

This article records the detailed process of down...

Summary of how to add root permissions to users in Linux

1. Add a user . First, use the adduser command to...

MySQL learning record: bloody incident caused by KEY partition

Demand background Part of the data in the busines...