Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Pointing to context
The execution context is a concept in the language specification. In plain English, it means that we do some preparation before a function is executed. Everything that a function might use in its execution can be found in the execution context, which is the context in which the function is executed. Variables from the closure of the external scope), function parameters, and the value of this object. The call stack is a collection of execution environments.
This is the JavaScript keyword and an attribute of the current execution context object. This has different meanings in different environments and under different functions. In the browser context this points to window, while in node context this points to Global. Although we can access global objects differently in different environments, there is a common way to access global objects in different environments. This is globalThis
var one = 1
Copy the code
This variable is a global variable, a property of a global object, whose value we access through window.one. This variable can also be accessed from the browser via this.one, self.one and frames.
var tut = {
title :"machine learning".description:function(){
console.log(this.title);//"machine learning"
console.log(window)//window}}; tut.description();Copy the code
When we are inside an object this refers to the tut object, meaning that this no longer refers to the global object.
function Article(){
return this;
}
console.log(Article());//window
Copy the code
Create a function, return this, call the function to see the return value, in this case this points to the global object Window. However, in strict mode, undefined is returned
function Article(){
"use strict"
return this;
}
Copy the code
In the class this
We all know that the class keyword was introduced in ES6, and that JavaScript began to support object-oriented programming at the language level. In fact, class is nothing new, it is a syntax sugar, it is a function, not so simple to understand here, should be understood as a container. We’ve modeled a class before with functions and prototypes, but these are cumbersome and require many steps.
class Tut1{
constructor(){}
description(){}}function Tut2(){}
Tut2.prototype.description = function(){}
Copy the code
const Tut3 = (function(){
function Tut(){}
Tut.prototype.description = function(){}
Tut.cal = function(){}
window.Tut = Tut
})();
Copy the code