this 魔术变量
this永远指向,调用它的对象,默认指向window/全局对象。
1.全局作用域中的this
在全局作用域中,this指向 window/全局对象
。
console.log(this) // window对象
console.log(this === window) //true
2.直接调用
在函数被直接调用时,this 将指向全局对象。在浏览器环境中全局对象是 Window,在 Node.js 环境中是 Global。
function fn1() {
console.log(this)
}
fn1() // this->window
3.对象方法中
对象方法中,this指向当前对象
var obj = {
say: function () {
console.log(this);
}
}
obj.say(); //this->obj
4.箭头函数中this
箭头函数的this指向宿主对象
箭头函数中this指向不会被改变
箭头函数中没有 this, 它会绑定最近的非箭头函数作用域中的this。首先从它的父级作用域找,如果父级作用域还是箭头函数,就再往上找,一层一层的直到直到this的指向。
// 箭头函数中的this
let model = () => {
console.log(this);
};
model(); // this ==> window; 原因如下
// 由于model函数是箭头函数,所以自身不能绑定this,因此找它的上一级作用域
5.构造函数中this
构造函数中this指向实例化对象
function Person () {
console.log(this)
this.name = '比克'
}
var obj = new Person() // 得到一个实例化对象,继承了Person函数的属性
console.log(obj)
6.事件中的this
事件中的this指向当前节点对象
document.querySelector('div').onclick = function () {
console.log(this) //<div></div>
}