SoFunction
Updated on 2025-04-07

Clever talk about this keyword in JavaScript

Compared with many other object-oriented languages, this represents the current object. For example, this in Java is determined during compilation. In JavaScript, this is dynamic binding, or runtime binding

This in Java

In the following code. This represents the p object.

public class Test { 
public static void main(String[] args) {
Person p = new Person("zmt",30);
();
}
}
class Person{ 
String name;
int age;
Person(String name,int age){
 = name;
 = age;
}
}

This in JavaScript

This in JavaScript has much richer meaning. It can be a global object, current object, or any object, depending entirely on how the function is called. There are several ways to call functions in JavaScript: call as object method, function call, constructor call, and use apply or call. Below we will discuss the meaning of this according to the different calling methods.

1. Call as a normal function

In ordinary functions, this represents a window object

function test(){
alert(this);
}
test();

2. Call as a constructor

When it is called as a constructor, it represents the current object. This is the same as Java.

function Person(name,age){
 = name;
 = age;
}

The above is the keyword this in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!