1. Summarize this in three sentences.

  1. Global scope: This in the global scope refers to window.
  2. Function scope: This in a method refers to the object on which it is called; Point to window if there is no caller.
  3. Constructor: This in the constructor (or ES6+ class) refers to the newly generated instance object.

2, global scope: global this, point to window;

Var c = 30; var c = 30; var c = 30; var c = 30; var c = 30; var c = 30; alert(this.c); // 30 var value = 200; Var fun2 = function(){// output 200 console.log(this.value); }; fun2();

Function scope: This in a method refers to the object that called it, or window if there is no caller.

  • A method has an object to which it belongs: this points to the object that called it
Var obj = {value: 100, get: function () {// output 100 console.log(this.value); // output {value: 100, get: [Function]}, console.log(this); return this.value; }}; console.log(obj.get()); / / = > 100
  • Method has no object to belong to: this points to window, which is part of the system design. You can use the variable substitution method, which is usually named self/that instead of this.
Var obj = {value: 100, get: function(){var fun1 = function(){undefined console.log(this.value); // Print window console.log(this); }; fun1(); }}; obj.get();

This in the constructor (or ES6+ class) refers to the newly generated instance object.

// ES5 constructor function newClass (){this.name = "newClass"; } var obj = new NewClass(); console.log(obj.name); / / output newClass
Class Es6Class{constructor(){constructor(){this.name = "Es6Class "; } } let obj = new Es6Class(); console.log(obj.name); / / output es6Class

Special thanks: pull gou education front-end high salary training camp