this (computer programming)

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity which the currently running code is a part of.

In many object-oriented programming languages, this (also called self or Me) is a variable that is used in instance methods to refer to the object on which they are working.

Smalltalk and others, such as Object Pascal, Perl, Python, Ruby, Rust, Objective-C, DataFlex and Swift, use self.

Some languages require it explicitly; others use lexical scoping to use it implicitly to make symbols within their class visible.

[2] In some languages, for example C++, Java, and Raku this or self is a keyword, and the variable automatically exists in instance methods.

Rust requires the self object to be called &self or self, depending on whether the invoked function borrows the invocant, or moves it in, respectively.

For example, in the following Perl code for the factorial, the token __SUB__ is a reference to the current function: By contrast, in C++ (using an explicit this for clarity, though not necessary) the this binds to the object itself, but if the class method was declared "virtual" i.e. polymorphic in the base, it's resolved via dynamic dispatch so that derived classes can override it.

However, within C# value types, this has quite different semantics, being similar to an ordinary mutable variable reference, and can even occur on the left side of an assignment.

In such a situation, for example, the statement var n = localAndFieldname; within the method will assign the type and value of the local variable localAndFieldname to n, whereas the statement var n = this.localAndFieldname; will assign the type and value of the outer field variable to n.[11] In D this in a class, struct, or union method refers to an immutable reference of the instance of the enclosing aggregate.

In the first version of D, the keyword this is used as a pointer to the instance of the object the method is bound to, while in D2 it has the character of an implicit ref function argument.

[13] In JavaScript, which is a programming or scripting language used extensively in web browsers, this is an important keyword, although what it evaluates to depends on where it is used.

For example: Notably, JavaScript makes use of both this and the related keyword self[17] (in contrast to most other languages which tend to employ one or the other), with self being restricted specifically to web workers.

[18] Finally, as a reliable way of specifically referencing the global (window or equivalent) object, JavaScript features the globalThis keyword.

[21] Also starting with PowerShell 5.0, which adds a formal syntax to define classes and other user-defined types,[22] $this variable describes the current instance of the object.

Functions designed to be analogous to instance methods in more traditionally object-oriented languages must explicitly take self as their first parameter.