全局作用域或者普通函数中的this指向全局对象window
console.log(this) //window
//函数声明式
function fun1(){
console.log(this); //window
}
fun1();
//函数表达式
var fun=function(){
console.log(this) //window
}
fun();
//自指向函数
(function(){
console.log(this) //window
})
();
//方法中谁调用this,this就指向谁
//对象方法调用
var person ={
xx:function(){
console.log(this) //object{xx:xx()}
}
}
person.xx();
//事件绑定
var btn =document.querySelector('button');
btn.onclick=function(){
console.log(this) //this指向按钮标签
}
//事件监听
var btn =document.querySelector('button');
btn.addEventListener('click',function(){
console.log(this); //this指向按钮标签
})
构造函数创建对象,this的指向实例对象
//1.普通函数
function Person(name) {
this.name=name;
console.log(this) //this指向window
}
Person('xx')
//2.构造函数
function Person(name){
this.name=name;
console.log(this)
that = this
}
var Person = new Person('张三')
console.log(that===Person)//this指向Person实例对象Object {name:'张三'}
箭头函数 指向外层作用域的函数
var obj={
xx:function(){
console.log(this);
},
x:()=>{
console.log(this)
}
}
obj.xx(); //指向object{}对象 这个对象里的方法调用this,this指向这个对象方法
obj.x();//指向外层作用域wondow
apply与call改变this指向
var obj1 ={
name:'张三',
xx:function(){
console.log(this.name)
}
}
obj2={
name:'李四'
}
obj1.xx(); //正常调用 --张三
obj1.xx.call(obj2);//用call调用obj1下的方法时传入obj2这个对象作为参数
// --李四(改变了this的指向)