this的指向问题一直是面试的重中之重,深究起来很多人都不能完整地答出this的指向问题。这篇文章将完整地讲述各种函数的this指向问题。下一篇文章介绍了如何通过call、apply、bind来改变this指向,附上入口:改变this指向
建议收藏。前端技术交流Q群:610408494
this就是“这个、当前”的意思,它的指向一直指向当前函数的运行环境。
1. 普通函数
普通函数的this指向调用这个函数的对象,默认是window。严格模式情况下指向undefined。
函数被window调用的话,必定指向window,无论是否是严格模式。
function A() {
console.log(this)
}
A(); //window
window.A();//window
function B() {
"use strict"
console.log(this)
}
B(); //undefined
window.B(); //window
2. 自执行函数
自执行函数的this指向window
(function B(){
console.log(this) //指向window
})()
3. 构造函数
this指向new出来的实例对象,而且优先级是最高的,不能被改变
function D(name,age) {
this.name=name
this.age=age
this.say=function(word) {
console.log(this,word)
//D {name: '刘禅', age: 99, say: ƒ} '本少爷从不坑爹'
}
}
let ls = new D('刘禅',99)
ls.say('本少爷从不坑爹');
4.事件处理函数
this指向绑定事件的元素
const eLi =document.querySelector('.eLi')
eLi.onclick=function(){
console.log(this)
// <div class="eLi">按钮</div>
}
5.箭头函数
function E(name,age){
this.name=name
this.age=age
this.say=()=>{
console.log(this)
// {name: '鲁班七号', age: 99, say: ƒ}
}
}
let lbqh=new E('鲁班七号',99)
lbqh.say('来打我呀,抓不到我的');
箭头函数的this指向的是它外面的第一个不是箭头函数的函数的 this, 在定义时就确定了,不能被改变。但是如果想在箭头函数内部访问外部的this,比如Vue框架中比较常用const _this=this、const that = this来定一个新的变量,在箭头函数内部就可以调用外部Vue上的方法和data了。
468

被折叠的 条评论
为什么被折叠?



