跳到主内容
← 返回题库
八股概念3/5 中等前端 · 一面 ★ 0 · 浏览 7

JS 中 this 的绑定规则与优先级判断

阅读下面的代码,说出每个 console.log 的输出,并解释原因: const obj = { name: ‘obj’, getName() { return this.name; }, getNameArrow: () => this.name }; const fn = obj.getName; console.log(obj.getName()); console.log(fn()); console.log(obj.getNameArrow()); console.log(obj.getName.call({name:‘ctx’})); function P(){ this.x = 1; } console.log(new P().x); 要求:明确说明 this 的绑定优先级,以及严格模式下的差异。

参考答案

先自己想 30 秒再看答案,比直接读一遍有用得多。

追问链

  1. 1. 手写一个 bind,要求支持 new 调用且返回实例的 instanceof 判断正确;在 React 类组件中把方法作为回调传递为什么会丢 this,怎么解决