this, self, and Me are
keywords used in some computer
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s to refer to the object, class, or other entity which the currently running code is a part of. The entity referred to thus depends on the
execution context (such as which object has its method called). Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, these keywords can disambiguate variables and functions with the same name.
Object-oriented programming
In many
object-oriented
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s,
this
(also called
self
or
Me
) is a variable that is used in
instance method
A method in object-oriented programming (OOP) is a Procedure (computer science), procedure associated with an Object (computer science), object, and generally also a Message passing, message. An object consists of ''state data'' and ''behavior''; ...
s to refer to the object on which they are working. The first OO language,
SIMULA 67, used
this
to explicitly reference the local object.
C++ and languages which derive in style from it (such as
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
,
C#,
D, and
PHP) also generally use
this
.
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
and others, such as
Object Pascal
Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods.
T ...
,
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
,
Python,
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
,
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
,
Objective-C
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
,
DataFlex and
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIF ...
, use
self
. Microsoft's
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (classic), the original Visual Basic suppo ...
uses
Me
.
The concept is similar in all languages:
this
is usually an immutable
reference
A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
or
pointer which refers to the current object; the current object often being the code that acts as 'parent' or 'invocant' to the
property
Property is a system of rights that gives people legal control of valuable things, and also refers to the valuable things themselves. Depending on the nature of the property, an owner of property may have the right to consume, alter, share, re ...
,
method
Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
, sub-routine or function that contains the
this
keyword. After an object is properly constructed, or instantiated,
this
is always a valid reference. Some languages require it explicitly; others use
lexical scoping
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
to use it implicitly to make symbols within their class visible. Or alternatively, the current object referred to by
this
may be an independent code object that has called the function or method containing the keyword
this
. Such a thing happens, for example, when a
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
event handler attached to an HTML tag in a web page calls a function containing the keyword
this
stored in the global space outside the document object; in that context,
this
will refer to the page element within the document object, not the enclosing window object.
In some languages, for example C++, Java, and Raku
this
or
self
is a
keyword, and the variable automatically exists in instance methods. In others, for example, Python, Rust, and Perl 5, the first
parameter
A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
of an instance method is such a reference. It needs to be specified explicitly. In Python and Perl, the parameter need not necessarily be named
this
or
self
; it can be named freely by the programmer like any other parameter. However, by informal convention, the first parameter of an instance method in Perl or Python is named
self
. 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.
Static method
A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be us ...
s in C++ or Java are not associated with instances but classes, and so cannot use
this
, because there is no object. In other languages, such as Ruby, Smalltalk, Objective-C, or Swift, the method is associated with a ''class object'' that is passed as
this
, and they are called
class method
A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be us ...
s. For class methods, Python uses
cls
to access to the ''class object''.
Subtleties and difficulties
When lexical scoping is used to infer
this
, the use of
this
in code, while not illegal, may raise warning bells to a maintenance programmer, although there are still legitimate uses of
this
in this case, such as referring to instance variables hidden by local variables of the same name, or if the method wants to return a reference to the current object, i.e.
this
, itself.
In some compilers (for example
GCC), pointers to C++ instance methods can be directly cast to a pointer of another type, with an explicit
this
pointer parameter.
Open recursion
The dispatch semantics of
this
, namely that method calls on
this
are dynamically dispatched, is known as open recursion, and means that these methods can be
overridden by derived classes or objects. By contrast, direct named recursion or
anonymous recursion
In computer science, anonymous recursion is Recursion (computer science), recursion which does not explicitly call a function by name. This can be done either explicitly, by using a higher-order function – passing in a function as an argument and ...
of a function uses closed recursion, with static dispatch. For example, in the following
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
code for the factorial, the token
__SUB__
is a reference to the current function:
use feature ":5.16";
sub
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.
unsigned int factorial(unsigned int n)
This example is artificial since this is direct recursion, so overriding the
factorial
method would override this function; more natural examples are when a method in a derived class calls the same method in a base class, or in cases of mutual recursion.
The
fragile base class problem has been blamed on open recursion, with the suggestion that invoking methods on
this
default to closed recursion (static dispatch) rather than open recursion (dynamic dispatch), only using open recursion when it is specifically requested; external calls (not using
this
) would be dynamically dispatched as usual. The way this is solved in practice in the JDK is through a certain programmer discipline; this discipline has been formalized by C. Ruby and G. T. Leavens; it consists of the following rules:
[Aldrich, Jonathan, and Kevin Donnelly.]
Selective open recursion: Modular reasoning about components and inheritance.
SAVCBS 2004 Specification and Verification of Component-Based Systems (2004): 26. citing for the JDK-adopted solution C. Ruby and G. T. Leavens. "Safely Creating Correct Subclasses without Seeing Superclass Code". In Object-Oriented Programming Systems, Languages, and Applications, October 2000. also available a
technical report TR #00-05d
/ref>
* No code invokes public
methods on this
.
* Code that can be reused internally (by invocation from other methods of the same class) is encapsulated in a protected
or private
method; if it needs to be exposed directly to the users as well, then a wrapper public
method calls the internal method.
* The previous recommendation can be relaxed for pure methods.
Implementations
C++
Early versions of C++ would let the this
pointer be changed; by doing so a programmer could change which object a method was working on. This feature was eventually removed, and now this
in C++ is an r-value.[
]
Early versions of C++ did not include references and it has been suggested that had they been so in C++ from the beginning, this
would have been a reference, not a pointer.
C++ lets objects destroy themselves with the source code statement: delete this
.
C#
The keyword this
in C# works the same way as in Java, for reference types. However, within C# value type In certain computer programming languages, data types are classified as either value types or reference types, where reference types are always implicitly accessed via references, whereas value type variables directly contain the values themselves.
...
s, this
has quite different semantics, being similar to an ordinary mutable variable reference, and can even occur on the left side of an assignment.
One use of this
in C# is to allow reference to an outer field variable within a method that contains a local variable that has the same name. 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
.
D
In D this
in a class, struct, or union method refers to an immutable reference of the instance of the enclosing aggregate. Classes are reference
A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
types, and structs and unions are value types. 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.
Dylan
In the programming language Dylan, which is an object-oriented language that supports multimethods and doesn't have a concept of this
, sending a message to an object is still kept in the syntax. The two forms below work in the same way; the differences are just syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
.
object.method(param1, param2)
and
method (object, param1, param2)
Eiffel
Within a class text, the current type is the type obtained from the current class. Within features (routines, commands and queries) of a class, one may use the keyword Current
to reference the current class and its features. The use of the keyword Current
is optional as the keyword Current
is implied by simply referring to the name of the current class feature openly. For example: One might have a feature `foo' in a class MY_CLASS and refer to it by:
class
MY_CLASS
feature -- Access
foo: INTEGER
my_function: INTEGER
do
Result := foo
end
end
Line #10 (above) has the implied reference to Current
by the call to simple `foo'.
Line #10 (below) has the explicit reference to Current
by the call to `Current.foo'.
class
MY_CLASS
feature -- Access
foo: INTEGER
my_function: INTEGER
do
Result := Current.foo
end
end
Either approach is acceptable to the compiler, but the implied version (e.g. x := foo
) is preferred as it is less verbose.
As with other languages, there are times when the use of the keyword Current
is mandated, such as:
class
MY_CLASS
feature -- Access
my_command
-- Create MY_OTHER_CLASS with `Current'
local
x: MY_OTHER_CLASS
do
create x.make_with_something (Current)
end
end
In the case of the code above, the call on line #11 to make_with_something is passing the current class by explicitly passing the keyword Current
.
Java
The keyword this
is a Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
language keyword that represents the current instance of the class in which it appears. It is used to access class variables and methods.
Since all instance methods are virtual in Java, this
can never be null.
JavaScript
In JavaScript, which is a programming or scripting language
In computing, a script is a relatively short and simple set of instructions that typically automation, automate an otherwise manual process. The act of writing a script is called scripting. A scripting language or script language is a programming ...
used extensively in web browsers, this
is an important keyword, although what it evaluates to depends on where it is used.
* When used outside any function, in global space, this
refers to the enclosing object, which in this case is the enclosing browser window, the window
object.
* When used in a function defined in the global space, what the keyword this
refers to depends on how the function is called. When such a function is called directly (e.g. f(x)
), this
will refer back to the global space in which the function is defined, and in which other global functions and variables may exist as well (or in strict mode, it is undefined
). If a global function containing this
is called as part of the event handler of an element in the document object, however, this
will refer to the calling HTML element.
* When a method is called using the new
keyword (e.g. var c = new Thing()
) then within Thing this
refers to the Thing object itself.
* When a function is attached as a property of an object and called as a method of that object (e.g. obj.f(x)
), this
will refer to the object that the function is contained within. It is even possible to manually specify this
when calling a function, by using the .call()
or .apply()
methods of the function object. For example, the method call obj.f(x)
could also be written as obj.f.call(obj, x)
.
To work around the different meaning of this
in nested functions such as DOM event handlers, it is a common idiom in JavaScript to save the this
reference of the calling object in a variable (commonly called that
or self
), and then use the variable to refer to the calling object in nested functions.
For example:
// In this example $ is a reference to the jQuery library
$(".element").hover(function() );
Notably, JavaScript makes use of both this
and the related keyword self
(in contrast to most other languages which tend to employ one or the other), with self
being restricted specifically to web workers.
Finally, as a reliable way of specifically referencing the global (window or equivalent) object, JavaScript features the globalThis
keyword.
Lua
In Lua, self
is created as syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
when functions are defined using the :
operator. When invoking a method using :
, the object being indexed will be implicitly given as the first argument to the function being invoked.
For example, the following two functions are equivalent:
local obj =
function obj.foo(arg1, arg2)
print(arg1, arg2) -- cannot use "self" here
end
function obj:bar(arg)
print(self, arg) -- "self" is an implicit first argument before arg
end
-- All functions can be invoked both ways, with "." or with ":"
obj:foo("Foo") -- equivalent to obj.foo(obj, "Foo")
obj.bar(obj, "Bar") -- equivalent to obj:bar("Bar")
Lua itself is not object-oriented, but when combined with another feature called metatables, the use of self
lets programmers define functions in a manner resembling object-oriented programming.
PowerShell
In PowerShell, the special automatic variable
In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in ...
$_
contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
"one", "two", "three" , %
Also starting with PowerShell 5.0, which adds a formal syntax to define classes and other user-defined types, $this
variable describes the current instance of the object.
Python
In Python, there is no keyword for this
. When a member function is called on an object, it invokes the member function with the same name on the object's class object, with the object automatically bound to the first argument of the function. Thus, the obligatory first parameter of instance methods serves as this
; this parameter is conventionally named self
, but can be named anything.
In class methods (created with the classmethod
decorator), the first argument refers to the class object itself, and is conventionally called cls
; these are primarily used for inheritable constructors,[''Unifying types and classes in Python 2.2,'' Guido van Rossum,]
Overriding the __new__ method
where the use of the class as a parameter allows subclassing the constructor. In static methods (created with the staticmethod
decorator), no special first argument exists.
Rust
In Rust, types are declared separately from the functions associated with them. Functions designed to be analogous to instance methods in more traditionally object-oriented languages must explicitly take self
as their first parameter. These functions can then be called using instance.method()
syntax sugar. For example:
let mut foo = Foo::new(); // must called as a type-specified function
foo.refer(); // prints "0". Foo::refer() has read-only access to the foo instance
foo.mutate(5); // mutates foo in place, permitted by the &mut specification, need foo to be declared mut
foo.consume(); // prints "5" and destroys foo, as Foo::consume() takes full ownership of self
// equivalent to foo.refer()
Foo::refer(foo); // compilation error: foo is out of scope
Self
The Self
In philosophy, the self is an individual's own being, knowledge, and values, and the relationship between these attributes.
The first-person perspective distinguishes selfhood from personal identity. Whereas "identity" is (literally) same ...
language is named after this use of "self".
Xbase++
Self
is strictly used within methods of a class.
Another way to refer to Self
is to use ::
.
See also
*
*
*
*
*
References
Further reading
* Meyers, Scott, 1995. ''More Effective C++: 35 New Ways to Improve Your Programs and Designs''. Scott Meyers
* Stroustrup, Bjarne, 1994. ''The Design and Evolution of C++''. Addison-Wesley Pub. Co. Bjarne Stroustrup
{{DEFAULTSORT:This (Computer Programming)
Object-oriented programming