这个属性范围在javascript中 [英] this property scope in javascript

查看:82
本文介绍了这个属性范围在javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,

  var a = document.getElementById(demo); 
a.onclick = function(){
alert(this.innerHTML)
setTimeout(function(){
alert(this.innerHTML)
},1000) ;
}

我从第一个警报语句得到正确的innerHTML值。但我得到未定义的值在第二个警报语句。

因为在函数中你有嵌套的函数,在嵌套函数中<$ c $



所以,你可以这样使用:

  var a = document.getElementById(demo); 
a.onclick = function(){
var that = this;
alert(this.innerHTML)
setTimeout(function(){
alert(that.innerHTML)
},1000);
}

或者,您可以使用bind方法:

  var a = document.getElementById(demo); 
a.onclick = function(){
// var that = this;
alert(this.innerHTML)
setTimeout(function(){
alert(this.innerHTML)
} .bind(this),1000); //现在这指的是点击的元素
}


I have a code,

var a= document.getElementById("demo");
a.onclick = function(){
   alert(this.innerHTML)
   setTimeout(function(){
        alert(this.innerHTML)
  },1000);
}

I got correct innerHTML value from first alert statement. But i got undefined value in second alert statement. Can anyone explain this?

解决方案

Because within the function there you have function which is nested and in nested function the this keyword will refer to the window.

So, You can use like this:

var a= document.getElementById("demo");
a.onclick = function(){
   var that = this;
   alert(this.innerHTML)
   setTimeout(function(){
        alert(that.innerHTML)
  },1000);
}

Alternatively, you may use bind method:

var a= document.getElementById("demo");
a.onclick = function(){
  //var that = this;
   alert(this.innerHTML)
   setTimeout(function(){
        alert(this.innerHTML)
  }.bind(this),1000); // now this refers to the clicked element
}

这篇关于这个属性范围在javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆