Context this in an Object

5

I am presenting as an exam to see my level of JS and I have several doubts. I took out 39/45 and my mistakes are as follows and I would like someone to clarify them a bit:

  

What will be displayed on the console when "this" calls the following method? (What is logged to the console as "this" when the following method was called?)

var myObj = {
  property : "that",
  whatsThis : function(that) {
    setTimeout(function () {
      console.log(this);
    }, 0);
  }
}

myObj.whatsThis("?");

My answer was that in case I thought it would be myObj but I do not understand much why is window the correct answer, I give an example where it did go well:

  

What is "this" when the following method is called? (What is "this" when the following method was called?)

var myObj = {
  property : "that",
  whatsThis : function(that) {
    return this;
  }
}
myObj.whatsThis("?");

I put myObj as an answer and it was correct and it was because when I return this I refer to the object and I ignore the parameter that happened because I do not do anything but one question here: if I put return this.property would print "? " true? since I'm changing the value to local property, right?

Well that's my doubt the other one is

  

Why should you use asynchronous processing in your JS code? (Why should you use asynchronous processing in your JavaScript code?)

     

Learn more about synchronous and asynchronous requests here: link

     

Note: There are 2 correct answers to this question.

     
  • To speed up requests on the server when they do not need authorization on the server - To speed up server requests as they do not need authorization checks on the server

  •   
  • To optimize the resource and task load in parallel - To optimize resource loading and parallelize tasks   Correct!

  •   
  • To prevent the server from crashing with multiple requests - To avoid server crashes due to multiple requests   Your Answer

  •   
  • To prevent the user interface from being responsive during task execution - To avoid your UI becoming unresponsive due to long-running tasks (Correct)

  •   

That is more theoretical and if it makes sense it is assumed that with asynchronous processing is to load other processes without freezing the screen, right? And if it freezes the screen is damaged and responsive? Or I did not understand much that last only there I was wrong.

Sorry in advance for the translation there are things that do not translate very well hehe

    
asked by Naoto Amari 10.01.2018 в 14:26
source

2 answers

4

In this case:

var myObj = {
  property : "that",
  whatsThis : function(that) {
    setTimeout(function() {
      console.log(this);
    }, 0);
  }
};

myObj.whatsThis("?");

You are returning the window object since in the function inside setTimeout () you are loading the context of the old function, therefore you are not inheriting it and it is returning the window object, but look in the example that I am going to put you next, it is practically the same but with a completely different result:

var myObj = {
  property : "that",
  whatsThis : function(that) {
    setTimeout(() => {
      console.log(this);
    }, 0);
  }
};

myObj.whatsThis("?");

If you look closely the result is the object myObj , but ... why? If you look closely I have declared the function using a slightly different syntax, they are called arrow functions , which DO NOT create a new context, therefore the result returns myObj instead of the object window (in the current example, there may be other situations in which it would not have to be the object window ).

Regarding this other question:

var myObj = {
  property : "that",
  whatsThis : function(that) {
    return this;
  }
}
myObj.whatsThis("?");
     

If I put return this.property would print "?" true? since I am changing the   value to local ownership, right?

No, if you write as you say return this.property would return "that" , so that you return the parameter that you sent to the function you should write return that;

//usando return this.property;
var myObj = {
  property : "that", //<<<<
  whatsThis : function( that ) {
    return this.property;
  }
}

console.log( myObj.whatsThis("?") );

//Usando return that;
var myObj = {
  property : "that",
  whatsThis : function( that ) {
    //                  ^^^^
    return that;
  }
}

console.log( myObj.whatsThis("?") );

I hope to have solved the doubts, as far as asynchronous processing is a very broad topic, it is better that you go reporting little by little on the Internet about this topic. I leave this post in Spanish that is pretty good .

    
answered by 10.01.2018 в 15:14
2

On the first question, let's analyze the flow and you will realize what happens:

1 var myObj = {
2   property : "that",
3   whatsThis : function(that) {
4     setTimeout(function () {
5       console.log(this);
6     }, 0);
7   }
8 }
9 myObj.whatsThis("?");
  • Lines 1-8 declare an object that has a string attribute and another attribute that is a function, so it is a method of the object. This is obvious, but after explaining the code, we explain everything.

  • Line 9 calls the method with the '?' parameter. Therefore the parameter that is worth '?' (line 3).
  • The context ( this ) within the method during execution is myObj .
  • Line 4 calls setTimeout, passing as a function the code: function() {console.log(this);}

  • setTimeout puts the declared function in the execution queue. Since the wait time is 0, as soon as the main execution thread ends, it will be executed.

  • Finish the main thread.
  • The Javascript interpreter looks for what is pending to be executed, finds the function and executes it in the global context, therefore this is window . If we had used bind or we would have declared the function using the notation "flecha" (fat arrow), the context would have remained:

var myObj = {
  property : "that",
  whatsThis : function(that) {
    function fn() {
      console.log(this);
    }
    setTimeout(fn.bind(this), 0);
  }
}

myObj.whatsThis("?");


var myObj2 = {
  property : "that2",
  whatsThis : function(that) {
   
    setTimeout(()=> console.log(this), 0);
  }
}

myObj2.whatsThis("?");

For your second question, imagine that you have a code that does something like

for (let i=0,i<99999,i++) {
  miFuncion(i); //función que tarda una 0.01s en ejecutarse
}

Since Javascript is not multi-threaded, for about 1000 seconds your browser would be frozen, the user could press buttons and nothing would happen.

But if you can do something like:

for (let i=0,i<99999,i++) {
  setTimeout(()=>miFuncion(i),0) //función que tarda una 0.01s en ejecutarse
}

It turns out that you have an execution queue of 99999 functions, but between each one of them the browser has the option of responding to the user's events in a relatively fast way, which would not be totally frozen, simply slowed down. That is why asynchronous execution avoids the lack of response from the UI

Here is a shorter example, just freeze for 3 seconds:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

$('#sinc').on('click',function () {
  for (let i=0;i<300;i++) {
    sleep(10);
  }
});

$('#sinc').on('click',function () {
  for (let i=0;i<300;i++) {
    setTimeout(sleep(10));
  }
});
$('#test').on('click',function () {
  console.log('Has clickado en el test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sinc">Ejecución sinc</button>
<button id="asinc">Ejecución asinc</button>
<button id="test"> Clicka aquí para comprobar la respuesta de la interfaz</button>
    
answered by 10.01.2018 в 15:26