Question about assigning variables in Ecmascript 5

Asked

Viewed 23 times

3

My doubt 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, it will fetch again the most updated value of window.getComputedStyle ? Or this reading is done only once?

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

  • I added another example to simulate what you want. It doesn’t change the answer but you can use more or less as suggested in the question.

1 answer

3


This reading is only once.

You have to re-read the value by calling the window.getComputedStyle each time. Independent of being with var, let and const.

What you can do is getter that does the work for you, and that’s Javascript ES5, so 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;
  }
}

Browser other questions tagged

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