总结前置:
1、普通函数:this指向window
2、对象函数:this指向调用它的对象
3、构造函数:没有return时,this指向调用它的对象,有return时,指向return返回的对象
4、绑定事件函数:this指向函数的调用者
5、定时器函数:this指向window
6、立即执行函数:this指向window
7、箭头函数:箭头函数没有this,只能向外层寻找,指向箭头函数被定义时所在的作用域。
8、使用apply,call,bind()可以更改函数this的指向。
使用方法:如
函数名.apply(对象);
使函数的this指向该对象。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>笔记:this的指向</title>
</head>
<body>
<button id="btn">点击我</button>
<script>
// 1、普通函数:指向window
function f1(){
console.log(this);//Window
}
f1();
// 2、对象函数:指向调用他的对象
var obj={
sayhi:function(){
console.log(this);//{sayhi: ƒ}
}
}
obj.sayhi();
//3、构造函数
function Star(name,age){
this.name=name;
this.age=age;
console.log(this);//没有return函数,指向调用他的对象
}
let p1=new Star('李峋',20);
function Star1(name,age){
this.name=name;
this.age=age;
let p={name:'朱韵'};
return p;//有return,指向返回的对象
}
let p11=new Star1('李峋',20);
console.log(p11);
//4、绑定事件函数:指向函数的调用者
var btn = document.querySelector('button');
btn.onclick = function () {
console.log(this); //<button id="btn">点击我</button>
}
//5、定时器函数:指向window
setTimeout(function(){
console.log(this);
},1000);
//6、立即执行函数:指向window
(function(a){
console.log(this);
})(1);
//7、箭头函数:箭头函数没有this,只能向外层寻找,指向函数被定义时所在的作用域。
//自定义箭头函数
let t=()=>{
console.log(this);//打印window
};
t();//注意加括号
//箭头函数作为对象方法时
let t1={
name:()=>{
console.log(this);//由于对象也没有this,再次向外寻找,打印window
}
};
t1.name();
//8、显示绑定:函数通过call,apply,bind方法绑定,this指向的就是指定的对象
function fun(){
console.log(this.age);
}
var person={age:20,fun};
var person2={age:18,fun};
var age=28;
fun();//28,this指向window
person.fun();//20,指向person,此处为隐式绑定
fun.call(person);//20,此时函数fun的this指向person,与第84行代码做对比
fun.apply(person2);//18,此时函数fun的this指向person2
fun.bind(person)();//20,此时函数fun的this又被绑定到了person上
</script>
</body>
</html>
借鉴: