ArticleslgStudy

computer science

This (computer programming)

This (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand This (computer programming) rather than just read about it. In short: 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. The entity referred to thus depends on the execution context (such as which object has its method called).

Key takeaways

  • This (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect This (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of This (computer programming) from memory before moving on to harder problems.

Reference excerpt

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. 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 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. 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, C#, D, and PHP) also generally use this. Smalltalk and others, such as Object Pascal, Perl, Python, Ruby, Rust, Objective-C, DataFlex and Swift, use self. Microsoft's Visual Basic uses Me. The concept is similar in all languages: this 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 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 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 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 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 methods 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 methods. 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 of a function uses closed recursion, with static dispatch. 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 is resolved via dynamic dispatch so that derived classes can override it.

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:

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;. However, this is valid only for objects which are heap-allocated.

Explicit object parameters In C++23, explicit object parameters (colloquially known as "deducing this") is a feature which allows explicitly naming the implicit this parameter in a member function, allowing templates to automatically deduce the object type, qualifiers, and value category.

This has also been used to create recursive lambdas:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with This (computer programming)

Start with the simplest possible case. Write down what This (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to This (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about This (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of This (computer programming)

In research
This (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses This (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
This (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics Object-oriented programming, so understanding it makes those chapters shorter.
In everyday life
Look for This (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study This (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what This (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain This (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is This (computer programming) in simple terms?

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. The entity referred to thus depends on the execution context (such as which object has its method called).

Why does This (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study This (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on This (computer programming).

Tags

  • Object-oriented programming

Keep exploring