SoFunction
Updated on 2025-03-04

JavaScript Execution context perspective detailed explanation of this usage

Preface

Using properties inside objects in methods inside objects is a very common requirement. However, JavaScript's scope mechanism does not support this. Based on this requirement, JavaScript has another set of this mechanism.

This is bound to the execution context, which means that there is this in each execution context. The execution context is mainly divided into three types: global execution context, function execution context and eval execution context, so there are only these three corresponding this - this in the global execution context, this in the function, and this in eval.

This in the global execution context

Global execution contextthisIt meanswindowobject's. This is alsothisand scope chainThe only intersection point, the bottom end of the scope chain containswindowObject, in the global execution contextthisIt also points towindowObject.

This in the function execution context

function foo() {
  (this);
}
foo();

Execute this code, and the printed one is alsowindowobject, which indicates that a function is called by default, whose execution contextthisIt also points towindowobject's.

Generally, there are three ways to set the function execution context.thisvalue:

1. Set the function's call method

let bar = {
  myName: "GeekBang",
  test1: 1,
};
function foo() {
   = "Geek Time";
}
(bar);
(bar);
(myName);

Execute this code and you will findfooInternal functionthisAlready pointed tobarObject, because by printingbarThe object can be seenbarofmyNameThe attribute has changed from "GeekBang" to "Geek Time", and is printed in the global execution context.myName, the JavaScript engine prompts that the variable is undefined. In fact, exceptcallMethod, you can also usebindandapplyMethod to set the function execution contextthis

2. Call method settings through object

var myObj = {
  name: "Geek Time",
  showThis: function () {
    (this);
  },
};
();

Execute this code, you can see the final outputthisThe value refers tomyObjof. So, you can conclude that using an object to call a method inside it,thisIt points to the object itself.

Next, we slightly change the calling method andshowThisAssign to a global object and then call the object, the code is as follows:

var myObj = {
  name: "Geek Time",
  showThis: function () {
     = "GeekBang";
    (this);
  },
};
var foo = ;
foo();

Execute this code and you will findthisPointing to the globalwindowObject.

in conclusion:

Call a function in the global environment, the function inside thethisPoint to global variableswindow

A method inside is called through an object, and the execution context of the method isthisPoint to the object itself.

3. Set it through the constructor

function CreateObj() {
   = "Geek Time";
}
var myObj = new CreateObj();

When executednew CreateObj()At the time, the JavaScript engine did the following four things:

First create an empty objecttempObj

Then callMethod andtempObjAscallThe parameters of the method areCreateObjWhen the execution context is created, itthisJust point totempObjObject

Then executeCreateObjFunction, at this timeCreateObjFunction execution contextthisPointed totempObjObject

Last returntempObjObject

var tempObj = {};
(tempObj);
return tempObj;

In this way,newThe keyword has built a new object and the constructor isthisIn fact, it is the new object itself.

This design defects and response solutions

1. This in nested functions will not be inherited from outer functions

var myObj = {
  name: "Geek Time",
  showThis: function () {
    (this);
    function bar() {
      (this);
    }
    bar();
  },
};
();

After executing this code, you will find the functionbarIn-housethisPointing to the globalwindowObjects, and functionsshowThisIn-housethisPointing tomyObjObject.

This problem can be solved by a small trick, such asshowThisDeclare a variable in the functionthatUsed to savethis, and thenbarUsed in functionsthat. In fact, the essence of this method is tothisThe system is converted into a scoped system.

In fact, you can also use the arrow function in ES6 to solve this problem:

var myObj = {
  name: "Geek Time",
  showThis: function () {
    (this);
    var bar = () => {
      (this);
    };
    bar();
  },
};
();

This is because the arrow function in ES6 does not create its own execution context, so the arrow function inthisDepends on its external function.

2. This in normal functions points to the global object by default window

In actual work, we do not want the function execution contextthisBy default, it points to the global object, because this will break the boundaries of the data and cause some misoperations. If you want to make the function execute in the contextthisThe best way to point to an object is tocallMethod to display the call.

You can set up JavaScriptStrict modeTo solve (add in the first line"use strict";). In strict mode, a function is executed by default, and its function's execution contextthisThe value isundefined

The above is the detailed explanation of this usage from the perspective of JavaScript execution context. For more information about JavaScript execution context, please pay attention to my other related articles!