当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 从零开始学习前端JAVASCRIPT — JavaScript中this指向的四种情况

从零开始学习前端JAVASCRIPT — JavaScript中this指向的四种情况

2018年02月28日  | 移动技术网IT编程  | 我要评论

JavaScript中this的四种情况(非严格模式)


 

1、当this所在函数是事件处理函数时,this指向事件源。
2、当this所在函数是构造函数时,this指向new出来的对象。
3、this所在函数的所属对象是谁,this指向函数所属对象。
4、当this所在函数没有所属对象,this指向window对象

<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="utf-8" />  
        <title></title>  
    </head>  
    <body>  
          <div id="box" class="box" style="height: 100px; width:100px; background:#f3f3f3;"></div>
    </body>  
</html>  
  
<script type="text/javascript">  
//this  
//1、当this所在函数是事件处理函数时,this是事件源。  
document.getElementById("box").onclick = function(){  
 console.log(this); //this就是div.box 
}  
  
//2、当this所在函数是构造函数时,this是new出来的对象。  
function Person(name){  
    this.name = name;//this就是new出来的对象zhaosi
    console.log(this.name)
    this.eat = function(){  
        console.log(this.name+"is eatting");
    }  
}  
var zhaosi = new Person("赵四");  
  
// 3、this所在函数的所属对象是谁,this就是谁。  
function Person(name){  
 this.name = name;//就是new出来的对象liuneng
 this.eat = function(){  
     console.log(this.name+"is eatting");;//这个this是谁,谁调用eat,或者说调用eat时,前面的对象是谁,this就是谁  
 }  
}  
var liuneng = new Person("刘能");  
liuneng.eat();//这句话执行时,eat函数内部的this就是p1  
var laoqi = new Person("老七");  
laoqi.eat();//这句话执行时,eat函数内部的this就是p2  
  
//4、当this所在函数没有所属对象,this是window对象。全局变量都是window对象的属性。 
function test(){  
    console.log(this);//这个this就是window  
}  
  
test();//window对象可以省略,所以,这句话就等价于window.test();  
  
//全局变量是window对象的属性  
var t = "大脚";  
  
console.log(window.t);  
  
var obj = {  
    name:"李四"
}  
  
console.log(window.obj.name);  
  
//this转移是经常碰到的问题  
//1)、注意区分this所在函数调用时的隶属对象
  
//2)、如果不希望被this折磨可以选用ES6中的箭头函数。  
  
</script> 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网