{{short description|In programming languages, the object or class the currently running code belongs to}} {{lowercase}} '''{{mono|this}}''', '''{{mono|self}}''', and '''{{mono|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. 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 <code>this</code> 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 programming languages, <code>this</code> (also called <code>self</code> or <code>Me</code>) is a variable that is used in instance methods to refer to the object on which they are working. The first OO language, SIMULA 67, used <code>this</code> to explicitly reference the local object.<ref>{{cite web |last1=Dahl |first1=Ole-Johan |author-link=Ole-Johan Dahl |last2=Myhrhaug |first2=Bjørn |last3=Nygaard |first3=Kristen |author3-link=Kristen Nygaard |date=1970 |url=http://www.edelweb.fr/Simula/#7 |title=Common Base Language, Norwegian Computing Center}}</ref>{{rp|4.3.2.3}} C++ and languages which derive in style from it (such as Java, C#, D, and PHP) also generally use <code>this</code>. Smalltalk and others, such as Object Pascal, Perl, Python, Ruby, Rust, Objective-C, DataFlex and Swift, use <code>self</code>. Microsoft's Visual Basic uses <code>Me</code>.

The concept is similar in all languages: <code>this</code> is usually an immutable reference or pointer which refers to the current object; the current object often being the code that acts as 'parent' or 'invocant' to the property, method, sub-routine or function that contains the <code>this</code> keyword. After an object is properly constructed, or instantiated, <code>this</code> is always a valid reference. Some languages require it explicitly; others use lexical scoping to use it implicitly to make symbols within their class visible. Or alternatively, the current object referred to by <code>this</code> may be an independent code object that has called the function or method containing the keyword <code>this</code>. Such a thing happens, for example, when a JavaScript event handler attached to an HTML tag in a web page calls a function containing the keyword <code>this</code> stored in the global space outside the document object; in that context, <code>this</code> will refer to the page element within the document object, not the enclosing window object.<ref>Powell, Thomas A, and Schneider, Fritz, 2012. ''JavaScript: The Complete Reference, Third Edition.'' McGraw-Hill. Chapter 11, ''Event Handling'', p 428. {{ISBN|978-0-07-174120-0}}</ref>

In some languages, for example C++, Java, and Raku <code>this</code> or <code>self</code> is a keyword, and the variable automatically exists in instance methods. In others, for example, Python, Rust, and Perl 5, the first parameter 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 <code>this</code> or <code>self</code>; 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 <code>self</code>. Rust requires the self object to be called <code>&self</code> or <code>self</code>, depending on whether the invoked function borrows the invocant, or moves it in, respectively.

Static methods in C++ or Java are not associated with instances but classes, and so cannot use <code>this</code>, 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 <code>this</code>, and they are called class methods. For class methods, Python uses <code>cls</code> to access to the ''class object''.

==Subtleties and difficulties== When lexical scoping is used to infer <code>this</code>, the use of <code>this</code> in code, while not illegal, may raise warning bells to a maintenance programmer, although there are still legitimate uses of <code>this</code> 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. <code>this</code>, 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 <code>this</code> pointer parameter.<ref>Using the GNU Compiler Collection (GCC) &ndash; [https://gcc.gnu.org/onlinedocs/gcc/Bound-member-functions.html Bound member functions]</ref>

===Open recursion=== The dispatch semantics of <code>this</code>, namely that method calls on <code>this</code> 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 of a function uses '''closed recursion''', with static dispatch. For example, in the following Perl code for the factorial, the token <code>__SUB__</code> is a reference to the current function: <syntaxhighlight lang="perl"> use feature ":5.16"; sub { my $x = shift; $x == 0 ? 1 : $x * __SUB__->( $x - 1 ); } </syntaxhighlight> By contrast, in C++ (using an explicit <code>this</code> for clarity, though not necessary) the <code>this</code> 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. <syntaxhighlight lang="cpp"> unsigned int factorial(unsigned int n) { if (n == 0) { return 1; } else { return n * this->factorial(n - 1); } } </syntaxhighlight> This example is artificial since this is direct recursion, so overriding the <code>factorial</code> 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.<ref>"[http://www.cs.ox.ac.uk/people/ralf.hinze/talks/Open.pdf Closed and Open Recursion]", [http://www.informatik.uni-bonn.de/~ralf Ralf Hinze], July 2007</ref><ref>[http://lambda-the-ultimate.org/node/3204 Open Recursion], ''[http://lambda-the-ultimate.org/ Lambda the Ultimate]''</ref>

The fragile base class problem has been blamed on open recursion, with the suggestion that invoking methods on <code>this</code> 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 <code>this</code>) would be dynamically dispatched as usual.<ref>"[https://www.cs.cmu.edu/~aldrich/papers/selective-open-recursion.pdf Selective Open Recursion: A Solution to the Fragile Base Class Problem]", Jonathan Aldrich</ref><ref>"[http://lambda-the-ultimate.org/classic/message12271.html Selective Open Recursion: A Solution to the Fragile Base Class Problem]", ''[http://lambda-the-ultimate.org/ Lambda the Ultimate]''</ref> 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:<ref name="JDK">Aldrich, Jonathan, and Kevin Donnelly. "[https://www.cs.cmu.edu/~aldrich/papers/savcbs04.pdf 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. {{doi|10.1145/353171.353186}} also available as [http://www.eecs.ucf.edu/~leavens/tech-reports/ISU/TR00-05/TR.pdf technical report TR #00-05d]</ref> * No code invokes <code>public</code> methods on <code>this</code>. * Code that can be reused internally (by invocation from other methods of the same class) is encapsulated in a <code>protected</code> or <code>private</code> method; if it needs to be exposed directly to the users as well, then a wrapper <code>public</code> method calls the internal method. * The previous recommendation can be relaxed for pure methods.

== Implementations ==

=== C++ === {{details|C++ classes}}

Early versions of C++ would let the <code>this</code> pointer be changed; by doing so a programmer could change which object a method was working on. This feature was eventually removed, and now <code>this</code> in C++ is an r-value.<ref name="C++03">{{cite book | year = 2003 | title = ISO/IEC 14882:2003(E): Programming Languages - C++ | publisher = ISO/IEC }} </ref>

Early versions of C++ did not include references and it has been suggested that had they been so in C++ from the beginning, <code>this</code> would have been a reference, not a pointer.<ref>Stroustrup: [http://www.stroustrup.com/bs_faq2.html#this C++ Style and Technique FAQ]</ref>

C++ lets objects destroy themselves with the source code statement: <code>delete this</code>.

=== C# === {{details|C Sharp (programming language)}} The keyword <code>this</code> in C# works the same way as in Java, for reference types. However, within C# value types, <code>this</code> 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 <code>this</code> 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 <code>var n = localAndFieldname;</code> within the method will assign the type and value of the local variable <code>localAndFieldname</code> to <code>n</code>, whereas the statement <code>var n = this.localAndFieldname;</code> will assign the type and value of the outer field variable to <code>n</code>.<ref>De Smet, Bart, 2011. ''C# 4.0 Unleashed.'' Sams Publishing, Indianapolis, USA. Chapter 4, ''Language Essentials'', p 210. {{ISBN|978-0-672-33079-7}}</ref>

=== D === In D <code>this</code> in a class, struct, or union method refers to an immutable reference of the instance of the enclosing aggregate. Classes are reference types, and structs and unions are value types. In the first version of D, the keyword <code>this</code> 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 <code>ref</code> function argument.

=== Dylan === In the programming language Dylan, which is an object-oriented language that supports multimethods and doesn't have a concept of <code>this</code>, 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. 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 <code>Current</code> to reference the current class and its features. The use of the keyword <code>Current</code> is optional as the keyword <code>Current</code> 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:

<syntaxhighlight lang="eiffel" line highlight="10"> class MY_CLASS feature -- Access foo: INTEGER my_function: INTEGER do Result := foo end end </syntaxhighlight><ref>NOTE: The line numbers are for reference purposes only. Eiffel does not have line numbers in the class text. However, there is a line number option in the Eiffel Studio IDE, which can be optionally turned on for reference purposes (e.g. pair programming, etc).</ref>

Line #10 (above) has the implied reference to <code>Current</code> by the call to simple `foo'.

Line #10 (below) has the explicit reference to <code>Current</code> by the call to `Current.foo'.

<syntaxhighlight lang="eiffel" line highlight="10"> class MY_CLASS feature -- Access foo: INTEGER my_function: INTEGER do Result := Current.foo end end </syntaxhighlight>

Either approach is acceptable to the compiler, but the implied version (e.g. <code>x := foo</code>) is preferred as it is less verbose.

As with other languages, there are times when the use of the keyword <code>Current</code> is mandated, such as:

<syntaxhighlight lang="eiffel" line highlight="11"> 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 </syntaxhighlight>

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 <code>Current</code>.

=== Java === {{details|Java (programming language)}} The keyword <code>this</code> is a Java 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, <code>this</code> can never be null.<ref>Barnes, D. and Kölling, M. ''Objects First with Java''. "...the reason for using this construct [this] is that we have a situation that is known as '''name overloading''' - the same name being used for two different entities... It is important to understand that the fields and the parameters are separate variables that exist independently of each other, even though they share similar names. A parameter and a field sharing a name is not a problem in Java."{{citation needed|date=February 2013}}</ref>

=== JavaScript === {{details|JavaScript}} In JavaScript, which is a programming or scripting language used extensively in web browsers, <code>this</code> is an important keyword, although what it evaluates to depends on where it is used.

* When used outside any function, in global space, <code>this</code> refers to the enclosing object, which in this case is the enclosing browser window, the <code>window</code> object. * When used in a function defined in the global space, what the keyword <code>this</code> refers to depends on how the function is called. When such a function is called directly (e.g. <code>f(x)</code>), <code>this</code> 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 <code>undefined</code>). If a global function containing <code>this</code> is called as part of the event handler of an element in the document object, however, <code>this</code> will refer to the calling HTML element. * When a method is called using the <code>new</code> keyword (e.g. <code>var c = new Thing()</code>) then within Thing <code>this</code> 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. <code>obj.f(x)</code>), <code>this</code> will refer to the object that the function is contained within.<ref>Crockford, Douglas, 2008. ''JavaScript: The Good Parts''. O'Reilly Media Inc. and Yahoo! Inc. Chapter 4, ''Functions'', p 28. {{ISBN|978-0-596-51774-8}}</ref><ref>Powell, Thomas A, and Schneider, Fritz, 2012. ''JavaScript: The Complete Reference, Third Edition.'' McGraw-Hill. Chapter 5, ''Functions'', pp 170&ndash;1. {{ISBN|978-0-07-174120-0}}</ref> It is even possible to manually specify <code>this</code> when calling a function, by using the <code>.call()</code> or <code>.apply()</code> methods of the function object.<ref>Goodman, Danny, with Morrison, Michael, 2004. ''JavaScript Bible, 5th Edition.'' Wiley Publishing, Inc., Indianapolis, USA. Chapter 33, ''Functions and Custom Objects'', p 987. {{ISBN|0-7645-5743-2}}</ref> For example, the method call <code>obj.f(x)</code> could also be written as <code>obj.f.call(obj, x)</code>.

To work around the different meaning of <code>this</code> in nested functions such as DOM event handlers, it is a common idiom in JavaScript to save the <code>this</code> reference of the calling object in a variable (commonly called <code>that</code> or <code>self</code>), and then use the variable to refer to the calling object in nested functions.

For example:

<syntaxhighlight lang="javascript"> // In this example $ is a reference to the jQuery library $(".element").hover(function() { // Here, both this and that point to the element under the mouse cursor. var that = this; $(this).find('.elements').each(function() { // Here, this points to the DOM element being iterated. // However, that still points to the element under the mouse cursor. $(this).addClass("highlight"); }); }); </syntaxhighlight>

Notably, JavaScript makes use of both <code>this</code> and the related keyword <code>self</code><ref>[https://developer.mozilla.org/en-US/docs/Web/API/Window/self ''Mozilla Developer Network'': Window.self]</ref> (in contrast to most other languages which tend to employ one or the other), with <code>self</code> being restricted specifically to web workers.<ref>[https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API ''Mozilla Developer Network'': Web Worker API]</ref>

Finally, as a reliable way of specifically referencing the global (window or equivalent) object, JavaScript features the <code>globalThis</code> keyword.<ref>[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis ''Mozilla Developer Network'': globalThis]</ref>

=== Lua === {{details|Lua (programming language)}} In Lua, <code>self</code> is created as syntactic sugar when functions are defined using the <code>:</code> operator.<ref>{{Cite web|url=https://www.lua.org/pil/16.html|title = Programming in Lua : 16}}</ref> When invoking a method using <code>:</code>, 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:

<syntaxhighlight lang="lua"> 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") </syntaxhighlight>

Lua itself is not object-oriented, but when combined with another feature called metatables, the use of <code>self</code> lets programmers define functions in a manner resembling object-oriented programming.

=== PowerShell === In PowerShell, the special automatic variable <code>$_</code> 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.<ref>{{Cite web|url=https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables|title=PowerShell: About Automatic Variables|last=msdn|website=docs.microsoft.com|language=en-us|access-date=2018-03-22}}</ref>

<syntaxhighlight lang="ps1"> "one", "two", "three" | % { write $_ } </syntaxhighlight>Also starting with PowerShell 5.0, which adds a formal syntax to define classes and other user-defined types,<ref>{{Cite web|url=https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes|title=about_Classes|last=msdn|website=docs.microsoft.com|language=en-us|access-date=2018-12-17}}</ref> <code>$this</code> variable describes the current instance of the object.

=== Python === In Python, there is no keyword for <code>this</code>. 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 <code>this</code>; this parameter is conventionally named <code>self</code>, but can be named anything.

In class methods (created with the <code>classmethod</code> decorator), the first argument refers to the class object itself, and is conventionally called <code>cls</code>; these are primarily used for inheritable constructors,<ref>''Unifying types and classes in Python 2.2,'' Guido van Rossum, "[https://www.python.org/download/releases/2.2.3/descrintro/#__new__ Overriding the __new__ method]"</ref> where the use of the class as a parameter allows subclassing the constructor. In static methods (created with the <code>staticmethod</code> 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 <code>self</code> as their first parameter. These functions can then be called using <code>instance.method()</code> syntax sugar. For example:

<syntaxhighlight lang="rust> struct Foo { bar: i32, }

impl Foo { fn new() -> Foo { Foo { bar: 0, } }

fn refer(&self) { println!("{}", self.bar); }

fn mutate(&mut self, baz: i32) { self.bar = baz; }

fn consume(self) { self.refer(); } } </syntaxhighlight>

This defines a type, <code>Foo</code>, which has four associated functions. The first, <code>Foo::new()</code>, is not an instance function and must be specified with the type prefix. The remaining three all take a <code>self</code> parameter in a variety of ways and can be called on a <code>Foo</code> instance using the dot-notation syntax sugar, which is equivalent to calling the type-qualified function name with an explicit <code>self</code> first parameter.

<syntaxhighlight lang="rust"> let mut foo: 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 </syntaxhighlight>

=== Self === The Self language is named after this use of "self".

=== Xbase++ === <code>Self</code> is strictly used within methods of a class. Another way to refer to <code>Self</code> is to use <code>::</code>.

== See also == * {{annotated link|Anonymous recursion}} * {{annotated link|Inheritance (object-oriented programming)}} * {{annotated link|Self-reference}} * {{annotated link|Schizophrenia (object-oriented programming)}} * {{annotated link|Program Segment Prefix}}

== References == {{Reflist|30em}}

==Further reading== * Meyers, Scott, 1995. ''More Effective C++: 35 New Ways to Improve Your Programs and Designs''. {{ISBN|0-201-63371-X}} Scott Meyers * Stroustrup, Bjarne, 1994. ''The Design and Evolution of C++''. Addison-Wesley Pub. Co. {{ISBN|0-201-54330-3}} Bjarne Stroustrup

{{DEFAULTSORT:This (Computer Programming)}} Category:Object-oriented programming