错误:this.style 未定义?

use*_*366 5 javascript

抱歉,我刚刚开始学习 javascript,提出了一个小问题。

所以我想制作隐藏的功能slika[0]

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

slika[0] = setTimeout(hide, 4000);
Run Code Online (Sandbox Code Playgroud)

错误是:

TypeError: this.style is undefined  
this.style.display ='none';
Run Code Online (Sandbox Code Playgroud)

the*_*eye 1

当您调用 时hidethis将是window对象,并且window对象没有style属性。这就是为什么你得到

this.style is undefined
Run Code Online (Sandbox Code Playgroud)

如果你想隐藏slika[0],那么你应该使用这样的bind函数hideslika[0]

setTimeout(hide.bind(slika[0]), 4000);
Run Code Online (Sandbox Code Playgroud)

现在,您已将 绑定slika[0]hide函数。因此,当hide被调用时,this将引用slika[0],并将显示样式设置为none

如果你想要一个通用函数,你可以简单地接受对象作为参数,就像这样

function hideObject(object) {
    object.style.display ='none';
}
Run Code Online (Sandbox Code Playgroud)