this的指向

📌 一、this 的 5 大绑定规则

1. 默认绑定(函数直接调用)

javascript 复制代码
function show() {
  console.log(this); // 浏览器环境:window(严格模式:undefined)
}
show(); // 直接调用

2. 隐式绑定(方法调用)

javascript 复制代码
const obj = {
  name: "obj",
  show: function() {
    console.log(this.name); // this → obj
  }
}
obj.show(); // "obj"

3. 显式绑定(call/apply/bind)

javascript 复制代码
function show() {
  console.log(this.name);
}
const ctx = { name: "ctx" };
show.call(ctx); // "ctx"(强制绑定this)

4. new 绑定(构造函数)

javascript 复制代码
function Person(name) {
  this.name = name; // this → 新创建的实例
}
const p = new Person("Tom");

5. 箭头函数(继承外层 this)

javascript 复制代码
const obj = {
  show: () => {
    console.log(this); // this → 外层作用域的this(此处是window)
  }
}
obj.show();

💡 二、经典面试题解析

题目1:对象方法中的普通函数

javascript 复制代码
const obj = {
  name: "obj",
  show: function() {
    setTimeout(function() {
      console.log(this.name); // 输出空(this指向window)
    }, 100)
  }
}
obj.show();

原因setTimeout 的回调函数是普通函数,this 默认绑定到全局对象。


题目2:对象方法中的箭头函数

javascript 复制代码
const obj = {
  name: "obj",
  show: function() {
    setTimeout(() => {
      console.log(this.name); // "obj"
    }, 100)
  }
}
obj.show();

原因 :箭头函数继承外层 show 方法的 this(即 obj)。


题目3:多层嵌套中的 this

javascript 复制代码
const obj = {
  name: "obj",
  outer: function() {
    function inner() {
      console.log(this.name); // 输出空(this指向window)
    }
    inner();
  }
}
obj.outer();

解决方法 :使用 inner = () => { ... }const that = this


题目4:call 无法改变箭头函数

javascript 复制代码
const arrowFn = () => console.log(this.name);
const obj = { name: "obj" };
arrowFn.call(obj); // 输出空(箭头函数this不可被修改)

结论 :箭头函数的 this 在定义时就固化,无法通过 call/apply/bind 改变。


题目5:构造函数中的箭头函数

javascript 复制代码
function Person() {
  this.name = "Tom";
  this.say = () => {
    console.log(this.name); // "Tom"
  }
}
const p = new Person();
const say = p.say;
say(); // "Tom"(箭头函数绑定到实例对象)

关键:箭头函数在构造函数中会永久绑定到实例对象。


🔑 三、this 判断口诀

  1. 普通函数调用 :看是否用 new → 是则绑定新对象,否则默认绑定全局对象(严格模式为 undefined
  2. 方法调用 :绑定到调用它的对象(obj.method()this=obj
  3. 显式绑定call/apply/bind 指定的对象优先
  4. 箭头函数 :向上找最近一层非箭头函数的 this
  5. 事件回调 :DOM 事件中 this 是触发事件的元素(除非用箭头函数)

⚠️ 四、常见陷阱

  1. 回调函数丢失 thisarray.map(function(){...}) 中的普通函数
  2. 间接引用const fn = obj.method; fn()this 丢失
  3. 闭包中的 this:嵌套函数默认绑定全局对象
  4. 严格模式差异 :函数直接调用时 this=undefined

回答: 我了解到的this指向主要包括以下几个部分: 首先是普通函数的this指向,如果在调用这个函数时没用new,this指向全局对象window,严格模式下为undefined。如果在调用这个函数的时候用new,this的指向为这个新的对象。

然后是对象中方法里面的this绑定到调用它的对象

然后是显示绑定比如说函数在执行的时候使用了call,apply,bind函数,this就会指向对应函数里面的对象

然后是箭头函数里面的this,他会继承外层作用域最近的非箭头函数的this

相关推荐
Uyker13 分钟前
微信小程序动态效果实战指南:从悬浮云朵到丝滑列表加载
前端·微信小程序·小程序
小小小小宇37 分钟前
前端按需引入总结
前端
小小小小宇1 小时前
React 的 DOM diff笔记
前端
小小小小宇1 小时前
react和vue DOM diff 简单对比
前端
我在北京coding1 小时前
6套bootstrap后台管理界面源码
前端·bootstrap·html
Carlos_sam1 小时前
Opnelayers:封装Popup
前端·javascript
MessiGo2 小时前
Javascript 编程基础(5)面向对象 | 5.1、构造函数实例化对象
开发语言·javascript·原型模式
前端小白从0开始2 小时前
Vue3项目实现WPS文件预览和内容回填功能
前端·javascript·vue.js·html5·wps·文档回填·文档在线预览
每次的天空2 小时前
Android第十三次面试总结基础
android·面试·职场和发展