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

How to install MySQL using yum on Centos7 and achieve remote connection

Centos7 uses yum to install MySQL and how to achi...

A brief discussion on Python's function knowledge

Table of contents Two major categories of functio...

Vue3 implements Message component example

Table of contents Component Design Defining the f...

Implementation of positioning CSS child elements relative to parent elements

Solution Add position:relative to the parent elem...

Analysis of the process of building a cluster environment with Apache and Tomcat

In fact, it is not difficult to build an Apache c...

CSS float (float, clear) popular explanation and experience sharing

I came into contact with CSS a long time ago, but...

Detailed explanation of three methods of JS interception string

JS provides three methods for intercepting string...

Basic understanding and use of HTML select option

Detailed explanation of HTML (select option) in ja...

CSS multi-column layout solution

1. Fixed width + adaptive Expected effect: fixed ...

Detailed tutorial on deploying apollo with docker

1. Introduction I won’t go into details about apo...

MySQL insert json problem

MySQL 5.7.8 and later began to support a native J...

How to clear the cache after using keep-alive in vue

What is keepalive? In normal development, some co...

The docker-maven-plugin plugin cannot pull the corresponding jar package

When using the docker-maven-plugin plug-in, Maven...