Error: this.style undefined?

Sorry my noobish question just started learning javascript.

So, I want to make a function that hides slika[0].

function hide() {
  this.style.display ='none';
};        

slika[0] = setTimeout(hide, 4000);

And the error:

TypeError: this.style is undefined  
this.style.display ='none';
+4
source share
1 answer

When you call hide, it thiswill be an object window, and windowdoes not have an attribute style. That's why you get

this.style is undefined

If you want to hide slika[0], you must bindfunction hidewith slika[0], for example

setTimeout(hide.bind(slika[0]), 4000);

You have now bound the function slika[0]to hide. Therefore, when called hide, it thiswill refer to slika[0], and it will set the display style to none.

, , ,

function hideObject(object) {
    object.style.display ='none';
}
+1

Source: https://habr.com/ru/post/1534100/


All Articles