"this" within object properties

Asked

Viewed 85 times

10

In the code below, the first console.log(this) returns the object example (so far so good). The second console.log(this) returns the object window.

Why does this happen? Why, even inside an object, let f2 goes into the global context?

In my initial conception, being within the context of f1, the this should remain the same.

let example = {
  f1: function() {
    console.log(this);
    let f2 = function() {
      console.log(this);
    }
    f2();
  }
}
example.f1();

  • https://i.stack.Imgur.com/oSp4t.jpg

  • is the famous scope ...

  • good reading: https://imasters.com.br/development/escopos-em-javascript

2 answers

5

In one method, the this references the owner object of the method. In a "normal" function references the global object (I say "normal" because it is not a method or event function).

In his example, the first this is within the method f1, soon that this is the object example (owner of f1):

let example = {
  f1: function() {
    console.log(this);
    let f2 = function() {
      console.log(this);
    }
    //f2();
  }
}
example.f1();

See above that it returns the content of example.

Already in the second this, as it is within the function f2 (which is some normal function with the name f2), returns the global object. O this is "scoped" within the function, ie the this inside f2 has nothing to do with the this inside f1, even though he was inside that.

If the this were in an event, for example, it would reference the element that called the event.

So often when we need the this within a function forEach within an event function, we store the this of the event in a variable to use it within the forEach:

document.getElementById("botao").addEventListener("click", function(){

   let el = this; // guarda o this numa variável
   ['a','b'].forEach(function(valor){

      // a variável "el" é igual ao this do evento
      // pois aqui o this referencia o objeto global
      if(el.value == valor){
         el.style.background = "red";
      }

   });

});
<button id="botao" value="b">Clique-me</button>

5

Why wasn’t Binding made of this in that capacity.

Perhaps the best way to see the this be like any argument: it has to be initialized with some value.

When you invoke a method (invokes a function through an object), the JS itself initializes the this with a reference to the object:

var obj = {
  val: 10,
  
  logValue() {
    console.log(this.val);
  }
}

obj.logValue();

It works, right? The this was initialized with a reference to obj, and therefore this.val is the same as obj.val.

Now what happens if we untie the function of obj?

var obj = {
  val: 10,
  
  logValue() {
    console.log(this.val);
  }
}

var func = obj.logValue;
func();

No longer works. this no longer refers to obj, refers to window, because it was not made the function Binding with obj.


In note, Binding can be done manually as well:

var obj = {
  val: 10,
  
  logValue() {
    console.log(this.val);
  }
}

var func = obj.logValue;
func.bind(obj)();

That’s basically what happens when you do obj.logValue(), Binding is automatically made for you.

If you know Python, it is similar to how the first argument is automatically initialized with a reference to the object, when you invoke a function through an object.

  • My impression or these logValue has a syntax error?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.