前言
this 指向问题一直是 JavaScript 中的重点与难点,也是面试与笔试的高频考点。
今天就来彻底弄清楚这个问题。
何为 this
this
是 JavaScript 中的关键字,在严格模式和非严格模式之间也会有一些差别。
-
全局环境
在全局执行环境中(在任何函数体外部),this 指向全局对象 在严格模式下,this 指向 undefined 浏览器环境下, this 指向 window
-
函数(运行内)环境
在函数内部,this的值取决于函数被调用的方式 严格模式下,this 默认指向undefined
this 指向
-
事件调用环境
this指向绑定事件的元素对象(即
event.currentTarget
)HTML事件处理程序、0级事件处理程序、2级事件处理程序均是此规律
document.body.onclick = function(e) { console.log(this == e.currentTarget); // true }
-
函数内部 this 指向
this 最终指向的是调用它的对象
-
全局环境下,调用函数, this 指向 window
var a = "window"; function fn() { console.log(this.a); } fn(); // window
-
作为对象方法的函数
-
方法函数分三种情况:命名函数、匿名函数、箭头函数
匿名函数(立即执行函数)的执行环境具有全局性 箭头函数的 this 指向上一级执行环境
let name = "window"; let obj = { name: "obj", f1: function() { console.log(this.name); }, f2: function() { let that = this; return function() { console.log(that.name); // that 访问上级作用域中的变量,形成闭包 console.log(this.name); } } }; let fn1 = obj.f1; // this 指向调用它的对象 obj obj.f1(); // obj // 相当于 window.fn1() ,this 指向调用它的对象 window fn1(); // window // obj.f2() = function() {console.log(this.name);} // obj.f2()() 相当于 (function() {console.log(this.name);})() // 匿名函数的执行环境为 **全局对象**,故 this 指向 window obj.f2()(); // window
-
-
构造函数
-
一般情况下 this 指向实例
特殊情况:构造函数中有 return 值
1. return 值不为对象或为 null ,this 指向规则不变 2. return 值为对象(不为null),this 指向该对象
-
-
箭头函数
-
全局环境下,箭头函数 this 指向全局对象
-
指向上一级作用域所在的对象(函数形成作用域,对象不形成作用域)
-
-
改变this指向
JavaScript中 call、apply、bind 方法可改变 this 指向