1、事件调用环境
谁触发事件,函数里面的this指向的就是谁。
.box{
width: 100px;
height: 100px;
background: #0a8cd2;
position: relative;
left: 0px;
transition: 1s;
}
.lili{
width: 100px;
height: 100px;
background: #0a8cd2;
position: relative;
left: 0px;
transition: 1s;
}
<div class="box"></div>
<div class="lili"></div>
let box = document.querySelector('.box');
let lili = document.querySelector('.lili');
box.onclick = move;
lili.onclick = move;
function move() {
this.style.left = '100px';
}
2、全局环境
- 浏览器环境: this指向window
- node环境: this 指向module.exports
3、函数内部
this指向函数的的调用对象
function func() {
console.log(this);
}
func(); // window (严格模式:undefined)
window.func(); // window
let obj = {
a: 10,
b: function(){
console.log(this);
}
}
obj.b(); // this === obj
let fun = obj.b;
fun(); // window
4、构造函数
构造函数中的this指向的是实例对象。
// 构造函数
function Fun() {
this.num = 10;
console.log(this);
}
let obj = new Fun();
console.log(obj.num); // 10
new运算符的作用
如果构造函数中有return
5、箭头函数
箭头函数中this指向定义处上一层作用域的this。
// 箭头函数
let obj3 = {
fun: () => {
console.log(this);
}
}
obj3.fun(); // window
6、修改this指向
call、apply和bind的第一个参数指定了函数的this指向。(箭头函数的this指向不可被修改。)
let person = {
fullname: "xiaohua"
}
let obj4 = {
fun1: function() {
console.log(this.fullname);
},
fun2: () => {
console.log(this.fullname);
}
}
obj4.fun1.call(person); // xiaohua
obj4.fun2.call(person); //undefined
obj4.fun1.bind(person)(); //xiaohua