1-普通函数、全局作用域、定时器
##this指向window
//普通函数中的this 指向window
function go(){
console.log(this);
}
go();//window
//定时器
<button id="btn">btn</button>
<script>
var btn = document.getElementById("btn");
btn.onclick = function(){
setTimeout(function(){
console.log(this);//window
},500)
}
</script>
2-方法
#this指向调用它的对象
<script>
var name = "window"
var obj = {
name:"javascript",
sayName(){
console.log(this.name);
},
wait(){
console.log(this.name);//javascript
setTimeout(function(){
console.log(this.name);
})
},
delay(){
setTimeout(()=>{
console.log(this.name);
})
},
layOut(){
setTimeout(function(){
console.log(this.name);
}.bind(this))
},
print(){
var that = this;
setTimeout(function(){
console.log(this.name);
}.bind(that))
}
}
obj.sayName();//javascript
obj.wait();//window
obj.delay();//javascript
obj.layOut();//javascript
obj.print();//javascript
</script>
3-构造函数和class中
#this指向使用new关键字实例化的对象
function Fun(){
console.log(this); //this指向的是fun 实例对象 指向创造的新对象,新对象赋值给了fun
}
var fun = new Fun()
class Person{
skill = "vue";
constructor(name,age){
this.name = name;
this.age = age;
}
}
var p = new Person("lisi",18);
console.log(p.name); //lisi
4-call、bind、apply
this指向当前上下文的this
<script>
function fn1(){
console.log(this);
}
var obj = {
name:"vue"
}
fn1.call(obj)
fn1();
var fn2 = fn1.bind(obj);
fn2()
</script>