day7,谈谈你对this的理解

416 阅读1分钟

this表示当前对象,this的指向是根据调用的上下文环境来决定的,默认指向window对象,指向window对象时可以省略不写。调用的上下文环境包括全局和局部。

全局环境:在< script>< /script>中,此时指向window对象

 <script>
  console.log(<strong>this</strong>);
 </script>

局部环境

1)在全局作用域下直接调用函数,this指向window

function func(){
 console.log(this) ;
}
func();

2)对象函数调用,哪个对象调用就指向哪个对象

<input type="button"id="btnOK" value="OK">
<script>
varbtnOK=document.getElementById("btnOK");
btnOK.οnclick=function(){
console.log(this);  //this指向btnOK对象
}
</script>

3) new 实例化对象,在构造函数中的this指向实例化对象。

var Show=function(){
this.myName="Mr.Cao";   //this指向obj对象
}
var obj=new Show();

4) 用call或apply改变this的指向

var Go=function(){
 this.address="深圳";
}
var Show=function(){
 console.log(this.address);//输出 深圳
}
var go=new Go();
Show.call(go);//改变Show方法的this指向go对象