“This” is a common part of the basic interview question, and there are numerous articles everywhere that list how this points to different contexts. But memorizing test questions is no match for actual development.

What happens if we remove this from js?

  • Global functions -> Write directlywindowWell, whythis
  • The arrow function -> does not exist in the bottomthisAgain, by the rules of closures, it is who it is
  • bind,apply,call-> < p style = “text-align: centerthisMetaprogramming, of course, is no longer needed, don’t you inside
  • Constructors, object methods -> (awkward)

In fact, this in JS is designed to implement an OOP pattern that looks like Java.

const a = new foo()
a.bar() 
Copy the code

In the code above, foo, the constructor, should point to a new object and return it as a result, while bar, the method, should access its corresponding instance object, a.

Let’s take another look at the statement

function foo() {console.log(this)}

function bar() {console.log(this)}

// In some unknown corner
foo.prototype.bar = bar
Copy the code

I don’t know who is the constructor and who is the instance method at declaration time.

New [fn](… Args) executes the constructor, using obj.[fn](… Args executes object methods. To determine what this is pointing to.

So in this function, you shouldn’t have called this, you should have reported an error. In lambda expressions that have a closure scope, this should be looked up by the rules of the closure.

Wait, what if js functions are scoped with closures?

Ah ah ah, no matter, directly point to the window, this was designed in a week, what else do you want, it’s not impossible to use…


Compared with many other languages, JS has a higher degree of dynamics, which is not always an advantage. Some of the dynamics that come from overly perfunctory design often cause various disasters, such as this.

The disaster of this comes from designers wanting to combine global functions, lambda expressions, constructors, and methods on objects. But this is not necessary.

The reason why other languages don’t have this problem is because other languages make it clear when global functions, lambda expressions, constructors, and methods on objects are declared, and don’t need to be dynamically determined.

USES the example of rust

pub struct ClassName {
    field: i32,}impl ClassName {
    // The static method new acts as the constructor and returns an instance of ClassName
    pub fn new(value: i32) -> ClassName {
        ClassName {
            field: value
        }
    }

    pub fn public_method(&self) {
        // The self declared in the method is implicitly declared in JS as this
        println!("from public method");
        self.private_method();
    }

    fn private_method(&self) {
        println!("from private method"); }}Copy the code

Scala’s design is significantly more sophisticated.

// The class declaration means that this is a constructor
class Point(xc: Int, yc: Int) {
   // The variables/constants declared in the constructor are properties of the object
   var x: Int = xc
   var y: Int = yc

   // The functions declared in the constructor are the methods of the object
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("The coordinate point of x:" + x);
      println ("The coordinates of y:"+ y); }}Copy the code

Today’s JS is no longer that JS. What efforts did TC39 Committee make on this issue?

First, the arrow function performs the function of a lambda expression in function. Accessing this in the arrow function will also look up the layers as a closure. Var _this = this has become a history (shi).

The global function “this” is already partially solved in strict mode.

Where this should really be used, the constructors and instance methods, are all inside the parentheses of the class declaration.

In general, in our code, this can only appear within the parentheses of a class.

class Point {
  constructor(x, y) {
    // Show the declared constructor
    this.x = x;
    this.y = y;
  }

  toString() {
    // Display declared object methods
    return '(' + this.x + ', ' + this.y + ') '; }}Copy the code

Call /apply/bind Because in my opinion, these three belong to the category of JS metaprogramming.

What is metaprogramming?

Metaprogramming, in which programs can be written to generate, manipulate, or change other programs while they are running.

In short, it’s about giving new interpretations at the code level and programming against the code. This can be the ability to generate new code from the original code, or it can be the ability to rewrite the original code.

For example, proxy lets users override operations on objects, call/apply/bind overwrites dynamic scoping rules inside functions (because arrow functions have no dynamic scoping, so it doesn’t work), and with is even more frightening.

Metaprogramming, on the other hand, is something that is not allowed in business code, and something that is not allowed in framework code.

I hope you won’t need this article by the time you use it.


Nowadays, many people choose to face the interview questions to learn as their own way of learning. Should take an examination actually however education and actual development are to have quite big discrepancy.

“This,” for example, is a common front line basic interview question, and there are tons of articles everywhere that list how “this” points to in different contexts. Some articles even come up with various “fancy” techniques, such as the proximity principle and various nesting techniques. Useful? I don’t think it’s any good. Instead, there are few articles that really talk about why this is designed and how it can be used.

The next article is going to talk about the majority of people have not written in the code of WeakMap WeakSet, if you think this article has some content, please kindly point a like ha.