Js中常见this指向问题
2020/2/24 5:02:41
本文主要是介绍Js中常见this指向问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
无论是工作或者面试中,this指向问题是经常遇到的。所以这篇文章把常见的指向问题列出来给大家,避免踩坑。首先我们要知道,在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了,也就是说,this的指向完全取决于函数调用的位置。因为this的取值是作用域环境的一部分,每次调用函数,都会在不同的作用域环境。
1:全局环境中
在浏览器环境严格模式中(区别于node),this默认指向window。立即执行函数,默认的定时器等函数,this也是指向window。
console.log(this === window) // true function fn(){ console.log(this === window) } fn() // true (function(){ console.log(this === window) // true })() setTimeout(function() { console.log(this === window); //true }, 500)
2:对象函数中
如果函数作为对象的一个属性被调用时,函数中的this指向该对象。
var x = 10 // 相当于 window.x = 10 var obj = { x: 20, f: function(){ console.log(this.x) }, s: function(){ console.log(this.x) // 20 function fn(){ console.log(this.x) } return fn // 函数f虽然是在obj.fn内部定义的,但是它仍然是一个普通的函数,this仍然指向window } } var fn = obj.f fn() // 10 obj.f() // 20 obj.s()() // 10
首先调用fn()
为什么结果为10,因为新建了变量fn
,相当于fn = function(){ console.log(this.x)}
, 函数中this默认指向window,故输出为10。而 obj.f()
中this 指向obj,所以this.x = obj.x
, 输出结果为20。
3:构造函数中
构造函数创建的实例的属性指向构造函数的prototype。
function Man(name){ this.name = name } Man.prototype.getName = function(){ // this指向 Man return this.name } const tom = new Man('tom') console.log(tom.getName()) // 'tom' // 切记请勿修改构造函数的返回值,将会改变默认指向,比如 function Man(name){ this.name = name return { name: 'lily' } } Man.prototype.getName = function(){ // this指向 Man return this.name } const tom = new Man('tom') console.log(tom.name) // 'lily'
4:箭头函数中
箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的,箭头函数中的this取决于该函数被创建时的作用域环境。
// 第一种情况 var x= 10 var obj ={ x: 20, f1: function(){ console.log(this.x) }, f2: () => { console.log(this.x) // 指向 window } } obj.f1() // 20 obj.f2() // 10 // 第二种情况 var name = "jack" var man = { name: 'tom', f1: function(){ // 这边的this和下面的setTimeout函数下的this相等 var that = this setTimeout(()=>{ console.log(this.name, that === this) // 'tom' true }, 0) }, f2: function(){ // 这边的this和下面的setTimeout函数下的this不相等 var that = this setTimeout(function(){ console.log(this.name, that === this) // 'jack' false }, 0) } } man.f1() // 'tom' true man.f2() // 'jack' false
setTimeout默认指向window,但是,在箭头函数中,this的作用域环境在man内,故this指向了man。也就是说此时的this可以忽略外围包裹的setTimeout定时器函数,看上一层及的作用域。
5:dom节点中
特别在是react中jsx语法中,我们通常要改变dom的this指向,不然获取不到指定的执函数。所以通常需要在函数声明使用bind绑定事件。
// html <button id="btn">myBtn</button> // js var name = 'window' var btn = document.getElementById('btn') btn.name = 'dom' var fn = function (){console.log(this.name)} btn.addEventListener('click', f()) // this指向 btn btn.addEventListener('click', f.bind(obj)) // this指向 window
本文涉及到的案例是相对比较常见,如果想更加深入的理解this,可以参考github上的一篇文章 ☛ 传送门
这篇关于Js中常见this指向问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05HTML 颜色
- 2024-10-05HTML 颜色名
- 2024-10-01AntDesign-Form-rules学习:轻松入门教程
- 2024-10-01classnames学习:轻松掌握前端中的类名管理
- 2024-09-30前端案例资料:新手入门必读教程
- 2024-09-30前端编程资料:新手入门必备教程
- 2024-09-30前端培训资料:新手入门必读教程
- 2024-09-30滚动吸顶项目实战:从入门到上手
- 2024-09-29HTML学习:span标签教程详解
- 2024-09-29HTML基础:button标签教程