Doubt over assignment of variables in Ecmascript 5

3

My question is related to the behavior of a variable, since it is assigned a dynamic value in it.

For example in the code:

var x_position = window.getComputedStyle(elemento).marginLeft;

Doubt: Every time I have to read the variable x_position , will it fetch the updated value from window.getComputedStyle again? Or is this reading done only once?

My question is specific to ES5 because at 6 we already have constants.

    
asked by anonymous 30.09.2017 / 23:01

1 answer

3

This reading is only once.

You need to reread the value by calling window.getComputedStyle each time. Regardless of being var , let and const .

What you can do is getter that does the work for you, and that is JavaScript ES5, therefore not supported by older browsers like IE8.

Example:

var props = {
  get cor() {
    return window.getComputedStyle(document.body).backgroundColor;
  }
}

setInterval(() => {
  console.log(props.cor);
}, 400);
body {
  background-color: red;
  animation: mudacor 3s infinite;
}

@keyframes mudacor {
  0% {
    background-color: red;
  }
  50% {
    background-color: yellow;
  }
  100% {
    background-color: red;
  }
}
    
30.09.2017 / 23:07