-
JavaScript中的this
- 在JavaScript中:this是函数调用(函数执行上下文).有四种函数调用类型
- 函数调用:alert('hello world')
- 方法调用:console.log('hello world')
- 构造函数调用:new Function()
- 间接调用: alert.call(undefined,'hello world')
- 每种调用类型都要看方式,如何定义上下文,因此this其行为与开发人员预期的不同
- 此外,严格模式下也会影响执行上下文
- 在JavaScript中:this是函数调用(函数执行上下文).有四种函数调用类型
-
理解this之前的准备
- 了解这篇文章之前,你需要大概知道这些东西
- 函数的作用域和作用域链
- 调用的上下文是this函数体内的值.
- 函数的调用是执行函数体的代码,或者只是简单的调用函数.例如:parseint函数调用parseInt('15')
- 了解这篇文章之前,你需要大概知道这些东西
-
this指向的原理: 简单来说,就是this指向调用者
-
this在函数调用中
- this是函数调用中的全局对象
- 在浏览器中,全局对象是window
- 平常我们调用一个简单函数,其实省略了window
- 在平常函数调用中,this指向window
-
function a() { console.log(this) } // window.a() 打印window // a() 打印window console.log(window.a() === a()) // true
-
this在严格模式下的this指向
- this在严格模式下指向undefined
- 要启用严格模式,需要在函数体顶部书写'use strict'
- 一旦启用,严格模式会影响执行上下文,使 this 在常规函数调用中未定义,这样执行上下文不再是全局对象
-
function a() { 'use strict' console.log(this) } a() // 打印undefined
-
this在对象上调用
- 在对象上调用方法时,this执行拥有这个方法的对象
-
let obj = { fn() { console.log(this === obj) //打印true }, } obj.fn()
-
易错点:对象里方法里面嵌套方法(函数里面嵌套函数)
-
误认为里面的函数this指向和外部函数this指向相同,都指向对象
-
let obj = { fn() { console.log(this === obj) //打印true let fn1 = function () { // 这个this指向的是window console.log(this) //打印window } return fn1() }, } obj.fn()
-
为了让内部函数的this和上级函数的this指向相同,有两种解决方法
-
使用箭头函数,箭头函数的this指向上级
-
更改this指向,使用call,bind,apply
-
-
-
构造函数this指向
- 构造函数的this指向实例化对象
-
function Fn() { console.log(this) //this指向new出来的实例化对象o } let o = new Fn()
-
js事件执行函数的this指向
- 事件执行函数的this指向事件源
-
document.documentElement.onclick = function () { console.log(this) //指向事件源HTML }
-
定时器里的函数this指向
- this指向window
-
setInterval(function () { console.log(this) }, 1000)
-
箭头函数的this指向
- 箭头函数函数不会创建自己的执行上下文,而是从外部函数中获取,如果外部没有函数,那么它的this指向window
-
function a() { return () => { console.log(this) // 因为上级函数为window调用,所以箭头函数也打印window } } a()()