What does '' this '' mean when we are working with objects in javascript?


This is an example of my doubt, why put "this" at the beginning instead of just putting "wheels = 4" or "seats = 1", etc. How can this help me when programming?

var Car = function() {
  this.wheels = 4;
  this.seats = 1;
  this.engines = 1;
asked by Ricardo A 25.06.2016 в 05:23

3 answers


In JavaScript this works a bit differently than in most object-oriented languages.

  • When using this in a function that is not called by any object, it is equivalent to the global object window .

    function hacerAlgo() {
        console.log(this); // window
  • When we use this within a function that exists within a clase u objeto , it refers to clase u objeto same.

    function Persona() {
        this.edad = 22; // this = Persona
    var Persona = {
        calcAge: function() {
            console.log(this); // this = Persona

Why put "this" at the beginning instead of just putting it   "wheels = 4" or "seats = 1"?

This is a design issue. In JavaScript it is required to use this in classes to denote that said variable is property of the class. If you do not use this , that variable is stored in the global scope .

answered by 25.06.2016 / 06:15

Correct me if I'm wrong:

I will generalize about the keyword this since it is used by several programming languages to refer to the "scope" of the element that is used.

Imagine that we have the following code:

class Miclase
    private int X;
    public void SetX(int X)
        this.X = X;

There are programming languages whose main focus goes to the local variables, before anything else, I mean, if in the code of SetX(X) the following had been set:

X = X; 

The compiler would not know what to do, saying "assign the value of parameter X to parameter X" . So this refers to the object that could always be present throughout the instance.

By doing this.X = X I am telling the compiler to assign the value of my parametron X to the private variable X that exists in my class.

It happens the same with any element, when using the word this you are defining that the element you want to call is that it has the priority level "low" as it is called.

Where you could define the priority levels as:

Variables/Funciones Locales  (Prioridad 1)
Variables/Funciones Globales (Prioridad 0)

It happens the same with the functions, imagine that in the System there is a function called Restar() and you have an element defined with the same name within a class or any other object:

funcion Restar()  
    // Implementacion ...

By default in any programming language, this element belongs to a class or a higher category object, so if we call the Restar() from the same instance, the function of the System will be more important than the one you have defined.

funcion Main()
    Restar(); // Llama a la función del Sistema.
    // ^ Llama a tu definición siempre que se encuentre dentro de la misma clase

Lastly, keyword this works as "pointer" (if so you can call it) to the current instance of the object, so all the above mentioned, can work .

this: MDN (English) :

answered by 25.06.2016 в 06:00

As other answers say, the keyword% this is used in several languages. Typically in object-oriented languages with classes (C ++ and Java in particular). In these languages, this is a reference to "this object", and it serves to specify which scope we are referring to when using the name of a variable (or field or property). In Javascript it is similar, but a little more varied and complicated.

In first approximation: this will be inside a function that is part of an object; when we invoke the function using this object, then this will refer to that object. Example:

var persona = {
     edad : 25,
     esMayor : function() {
         console.log("evaluando esMayor() , this=" + this + " edad=" + this.edad);
         return this.edad >= 18;

persona.edad = 17;

If the above is clear, we must note a couple of things (especially for those of us who come from OOP with classes). First: notice that we have not declared anything that resembles a "person" class, but an object; against appearances, we can not (at least not easily) create several instances of this "person". Second: we could ask ourselves "Is the reference this really resolved in execution time? In fact, here, this will always correspond to persona , no?" No, not necessarily. Example:

var perro = { edad : 10, esViejo : persona.esMayor } ;
console.log("perro:" + perro.esViejo());

(This is important to clarify that what matters is the object that is used to invoke the function, not the object where the function is "declared".)

Now, there is another scenario slightly different, special and important (in fact, corresponds to the example of the question). There is a very special type of functions in Javascript, the constructors (the language, unfortunately, does not differentiate them at the syntactic level - in principle, any function can be used as a constructor - in fact, this is not usually the case - the convention is to use capital letters in the name).

var Car = function() {  // esto es (casi seguramente) un constructor
  this.wheels = 4;
  this.seats = 1;

The "normal" use of a constructor is with the keyword new , which allows you to instantiate several objects (not based on a "class", but on a constructor, which defines a prototype)

var car1 = new Car();
var car2 = new Car();

What happens with the invocation of constructor with new ... important to understand but the relevant here is the behavior of this : in this case, Javascript first creates a new object and then calls the constructor using that object . Then, this , in that context, points to the new created object.

Finally, what happens if this is used in a global context, (outside a function, or in a function that is not called as property of an object)? In this case, this points to the "global object" ( window ). It is rare that one is interested in this.

For more details, similar question in SO (English)

answered by 25.06.2016 в 18:58