一、this–>undefined
ES6的严格模式中,如果调用函数中的this或者顶层this将会指向undefined。
<script type="module">
function fn(){
console.log(this);
}
fn(); //undefined
</script>
<script type="module">
console.log(this); //undefined
</script>
二、this–>window
- 非严格模式中函数或者顶层中调用this,会被指向window
- 回调函数中默认this的指向是window
- 当使用call、apply、bind时,如果带入的第一个参数是null或者undefined,this默认会被指向window
三、this–>上下文环境中的this
- 箭头函数
var obj={
a:function(){
setTimeout(()=>{
this.b();//this就是当前箭头函数外的上下文环境中this的指向
// setTimeout外面的this是什么这个箭头函数中的this就是什么
},500)
document.addEventListener("click",e=>{
this.clickhandler(e)
// 这里的this指向addEventListener函数外上下文环境中this的指向
});
},
b:function(){
console.log("aaa");
},
clickhandler:function(e){
}
}
- 对象的属性中this也是上下环境中this的指向
var c = 20;
var obj = {
c: 10,
a: this.c,
b: function () {
console.log(this.a);
},
}</