Why is there this in JS?

Why is there this in JS?

1. Demand

Suppose we have an object

var person = {
    name: 'Frank',
    age: 18,
    phone: '13812345678',
    sayHi: function(){
      //To be supplemented},
    sayBye: function(){
      //To be supplemented}
}

This person object has name and age attributes, and a sayHi method. The current requirement is:

Call person.sayHi(...) to print "Hello, I'm Frank , 18 years old."
Call person.sayBuy(...) and print "Goodbye, remember my name is Frank , if you want to make an appointment, call me, my phone number is 13812345678"
need

The request is that simple. By meeting this requirement, we can understand the essence of this .

2. Solution

var person = {
    ...
    sayHi: function(name, age){
      console.log('Hello, my name is ${name}, I am ${age} years old')
    },
    sayBye: function(name, phone){
      console.log('Goodbye, remember my name is ${name}, if you want to make an appointment with me, call me, my phone number is ${phone}')
    }
}

The calling method is

person.sayHi(person.name, person.age)
person.sayBye(person.name, person.phone)

Don’t worry, I know this code is stupid, I will improve it next.

3. The first improvement

In the above method, you have to select person.name as the parameter every time you call it, which is really stupid. It is better to pass in a person directly. The code is as follows:

var person = {
    ...
    sayHi: function(self){
      console.log('Hello, I am ${self.name}, ${self.age} years old')
    },
    sayBye: function(self){
      console.log('Goodbye, remember my name is ${self.name}, if you want to make an appointment with me, call me, my phone number is ${self.phone}')
    }
}

The calling method is

person.sayHi(person)
person.sayBye(person)

That's a little better, but the code is still silly.
Why can't we omit person in the parameter and just change it to person.sayHi() ?

4. Add sugar

The calling method most desired by developers is person.sayHi() So the question is, if person.sayHi() has no actual parameters, how does person.sayHi function receive person ?

  • Method 1: Still treat the first parameter self as person , so that the formal parameter will always have one more self than the actual parameter
  • Method 2: Hide self and then use the keyword this to access self .

The father of JS chose method 2 and used this to access self . The creator of Python chose method 1, leaving self as the first parameter.

The process is as follows:

// Before using this:
sayHi: function(self){
    console.log('Hello, I am ${self.name}, ${self.age} years old')
}
// After using this:
sayHi: function(){
    // this is self
    console.log('Hello, I am ${this.name}, ${this.age} years old')
}

5. Incomprehensible

After using this, the complete code is as follows:

var person = {
    name: 'Frank',
    age: 18,
    phone: '13812345678',
    sayHi: function(){
      console.log('Hello, I am ${this.name}, ${this.age} years old')
    },
    sayBye: function(){
      console.log('Goodbye, remember my name is ${this.name}, if you want to make an appointment with me, call me, my phone number is ${this.phone}')
    }
}

Now it's the newbie's turn to be confused. What on earth is this this ? Where did it come from?

this is the hidden first parameter. When you call person.sayHi() , the person "becomes" this .

6. Problems

Many JS experts disdain to use this , thinking that this is not simple enough. Therefore, the father of JS prepared call sugar-free .call method for experts.

person.sayHi.call(person) is equivalent to person.sayHi()

The first argument of .call is explicitly person , without any syntax sugar.

Therefore, experts usually use obj.fn.call(null,1,2,3) to manually disable this .

In this way, the parameter of person.sayHi.call can actually be any object.

That is to say, although person.sayHi is a method of person , it can be called on any object.

7. Objects and functions

JS has no classes or methods, only objects and functions.

After JS added the class keyword, it barely created a fake class.

this is the bridge between objects and functions.

Compared to JS , I prefer Python 's way, which does not use the this keyword but uses the self parameter, which is easier to understand.

This is the end of this article about why there is this in JS. For more information about why there is this in JS, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of this pointing in JS arrow function
  • The principle and direction of JavaScript this
  • 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

<<:  How to convert rows to columns in MySQL

>>:  Enter two numbers in html to realize addition, subtraction, multiplication and division functions

Recommend

Details of the order in which MySQL reads my.cnf

Table of contents The order in which MySQL reads ...

MySQL 5.7.17 installation and use graphic tutorial

MySQL is a relational database management system ...

JS implements multiple tab switching carousel

Carousel animation can improve the appearance and...

MySQL 8.0.22 installation and configuration method graphic tutorial

This article records the installation and configu...

Solution to docker suddenly not being accessible from the external network

According to the methods of the masters, the caus...

Using Vue3 (Part 1) Creating a Vue CLI Project

Table of contents 1. Official Documentation 2. Cr...

A brief discussion on the characteristics of CSS float

This article introduces the characteristics of CS...

WeChat applet implements jigsaw puzzle game

This article shares the specific code for impleme...

Detailed steps for installing Tomcat, MySQL and Redis with Docker

Table of contents Install Tomcat with Docker Use ...

CSS positioning layout (position, positioning layout skills)

1. What is positioning? The position attribute in...

The concept of MySQL tablespace fragmentation and solutions to related problems

Table of contents background What is tablespace f...

Introduction to several ways to introduce CSS in HTML

Table of contents 1. Embed CSS styles directly in...

MySQL complete collapse: detailed explanation of query filter conditions

Overview In actual business scenario applications...