前言
定义
- 函数被调用时,创建活动记录(执行上下文),this就是其中记录的其中一个属性
- this指向执行时的对象,函数的执行环境动态绑定的
判定规则
取决于函数的调用方式, 谁调用就是this就指向谁。
默认绑定-----作为普通函数调用
- this指向全局
- 单独拷贝出来后,this会丢失,变成全局变量
var name = 'globalName'; var myObject = { name: 'sven', getName: function(){ return this.name; } }; var getName = myObject.getName; console.log( getName() ); // globalName
隐式绑定----对象调用
- 哪个对象调用就指向哪个
- 如果这个函数包含多个对象,this指向的是离它最近的对象(上一级对象)
let obj = { b: 'cece', c: { d: function() { console.log(this.b) } } } console.log(obj.c.d()) //undefined
new 绑定 -- 构造函数
- 构造器中的this,指向返回的对象
function newfun() { this.name = 'steve' return '1' } const obj1 = new newfun() console.log(obj1.name) // steve function newfun() { this.name = 'steve' return { name: 'ce' } } const obj1 = new newfun() console.log(obj1.name) //ce
显示绑定(apply、call、bind)-后面有详细解说
- 改变函数的调用对象,第一个参数就是改变后这个函数的对象
箭头函数ES6
书写就能确定this的指向,编译时绑定
- 没有自己的this和arguments
- 箭头函数中的this指向上一级作用域的this(对象不能形成独立的作用域)
let obj12 = { a: { a1:() => { console.log(this) } } } obj12.a.a1() //window a1==>window let obj121 = { a: function(){ var a1 =() => { console.log(this) } a1() } } obj121.a() //obj121 a1==>a==>obj121
- 坑
//绑定事件 button.addEventListener('click', ()=>{ console.log(this == window) //true }) //原型上添加方法 Cat.prototype.sayName = () => { console.log(this == window) //true }
参考链接
7个关于JS中的this关键字面试题 - padding2020 - 博客园 (cnblogs.com) 推荐
5分钟带你搞懂 Javascript 中的this(包含apply、call、bind) - 掘金 (juejin.cn)