← 回到书房大厅Esc

FROM THE BOOKSHELF / A PAGE TO KEEP

技术
51 分钟

This 绑定规则与硬绑定实现

胡新宇

发布于 2026-05-21

本文详解 JavaScript this 的运行时绑定本质,涵盖默认绑定、隐式绑定与丢失场景、显式绑定(call/apply/bind)、new 绑定、箭头函数词法 this,以及绑定优先级和硬绑定的手写实现。

This 绑定规则与硬绑定实现

难度:⭐⭐⭐ | 预计阅读时间:25 分钟 | ECMAScript 2024

this 是 JavaScript 中最令人困惑的概念之一。与大多数面向对象语言不同,JavaScript 的 this 不是在编写时确定,而是在调用时根据调用方式动态绑定。ECMAScript 规范定义了四种绑定规则,加上箭头函数的词法 this,共五种确定 this 的机制。掌握这些规则是理解框架设计和避免运行时 bug 的基础。


目录

  1. this 的运行时绑定本质
  2. 默认绑定规则
  3. 隐式绑定与隐式丢失
  4. 显式绑定:call/apply/bind
  5. new 绑定与构造过程
  6. 箭头函数的词法 this
  7. 绑定优先级
  8. 硬绑定实现原理
  9. 实战案例
  10. 深度追问
  11. 总结表格

1. this 的运行时绑定本质

根据 ECMAScript §6.2.4,this 值通过 Reference Record 的 [[ThisValue]] 字段确定。当函数被调用时,引擎执行以下步骤:

// 概念模型:函数调用的 this 解析
// 1. 求值 MemberExpression(如 obj.foo)
// 2. 如果结果是 Reference,检查其 baseValue
// 3. 根据调用形式确定 thisValue
// 4. 调用 [[Call]](thisValue, argumentsList)

代码示例 1:同一函数不同 this

function identify() {
  return this.name;
}

const alice = { name: 'Alice', identify };
const bob = { name: 'Bob', identify };

console.log(alice.identify()); // 'Alice' — 隐式绑定
console.log(bob.identify());   // 'Bob' — 隐式绑定
console.log(identify());       // undefined(严格模式:TypeError)

2. 默认绑定规则

当函数以独立形式调用时,this 绑定到全局对象(非严格模式)或 undefined(严格模式):

// 代码示例 2:默认绑定
function showThis() {
  console.log(this);
}

// 非严格模式
showThis(); // globalThis (浏览器: window, Node.js: global)

// 严格模式
'use strict';
function showThisStrict() {
  console.log(this);
}
showThisStrict(); // undefined

Node.js 差异:

  • 模块顶层的 this 是 module.exports(CommonJS)或 undefined(ESM)
  • 全局的 this 在 REPL 中是 global
  • 文件中顶层 this === module.exports(CJS),this === undefined(ESM)
// Node.js CommonJS
console.log(this === module.exports); // true(模块顶层)

// Node.js ESM (test.mjs)
console.log(this); // undefined

3. 隐式绑定与隐式丢失

3.1 隐式绑定

当函数作为对象方法调用时,this 绑定到该对象:

// 代码示例 3:隐式绑定
const timer = {
  seconds: 0,
  start() {
    console.log(`Timer this: ${this === timer}`); // true
    this.seconds++;
  }
};

timer.start(); // Timer this: true

3.2 隐式丢失 — 最常见的 this 陷阱

// 代码示例 4:隐式丢失的四种场景
const obj = {
  value: 42,
  getValue() {
    return this.value;
  }
};

// 场景1:赋值给变量
const fn = obj.getValue;
console.log(fn()); // undefined(默认绑定)

// 场景2:作为回调传递
setTimeout(obj.getValue, 0); // undefined

// 场景3:函数参数传递
function callFn(callback) {
  callback(); // 默认绑定
}
callFn(obj.getValue); // undefined

// 场景4:解构
const { getValue } = obj;
getValue(); // undefined

4. 显式绑定:call/apply/bind

4.1 call 和 apply

// 代码示例 5:显式绑定
function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const person = { name: 'Alice' };

// call: 参数逐个传递
console.log(greet.call(person, 'Hello', '!')); // "Hello, Alice!"

// apply: 参数以数组传递
console.log(greet.apply(person, ['Hi', '?'])); // "Hi, Alice?"

4.2 bind — 创建硬绑定函数

const boundGreet = greet.bind(person, 'Hey');
console.log(boundGreet('.')); // "Hey, Alice."

// bind 的幂等性:再次 bind 无效
const rebind = boundGreet.bind({ name: 'Bob' });
console.log(rebind('!')); // "Hey, Alice!" — 首次 bind 优先

5. new 绑定与构造过程

new 操作符的内部步骤(规范 §13.2.2):

// 代码示例 6:new 的完整过程
function Person(name) {
  // 1. 创建新对象 {}
  // 2. 将新对象的 [[Prototype]] 设为 Person.prototype
  // 3. this 绑定到新对象
  this.name = name;
  // 4. 如果函数没有显式返回对象,返回 this
}

const p = new Person('Alice');
console.log(p.name); // 'Alice'
console.log(p instanceof Person); // true

构造函数返回值的影响

// 代码示例 7:构造函数返回对象的陷阱
function Factory(name) {
  this.name = name;
  return { custom: true }; // 显式返回对象
}

const f = new Factory('test');
console.log(f.name);   // undefined!
console.log(f.custom); // true — 返回了自定义对象

function Factory2(name) {
  this.name = name;
  return 42; // 返回原始值被忽略
}

const f2 = new Factory2('test');
console.log(f2.name); // 'test' — 正常工作

6. 箭头函数的词法 this

箭头函数没有自己的 this,继承自定义时的词法环境:

// 代码示例 8:箭头函数 vs 普通函数
const obj = {
  value: 42,
  
  // 普通方法
  regular() {
    setTimeout(function() {
      console.log(this.value); // undefined(默认绑定到 globalThis)
    }, 0);
  },
  
  // 箭头函数
  arrow() {
    setTimeout(() => {
      console.log(this.value); // 42(继承 arrow 方法的 this)
    }, 0);
  }
};

obj.regular();
obj.arrow();

注意:箭头函数不能被 new 调用,没有 prototype 属性,也不能通过 call/apply/bind 改变 this:

const arrowFn = () => this;
console.log(arrowFn.call({ x: 1 })); // 仍然是外层 this,不是 {x: 1}

7. 绑定优先级

从高到低:

new 绑定 > 显式绑定 (call/apply/bind) > 隐式绑定 > 默认绑定
// 代码示例 9:优先级验证
function foo() {
  return this.a;
}

const obj1 = { a: 1, foo };
const obj2 = { a: 2, foo };

// 隐式 vs 显式
console.log(obj1.foo.call(obj2)); // 2(显式 > 隐式)

// new vs 隐式
function Bar(val) { this.a = val; }
const obj3 = { a: 3, Bar };
const b = new obj3.Bar(4);
console.log(b.a); // 4(new > 隐式)

// new vs bind
const BoundBar = Bar.bind({ a: 5 });
const bb = new BoundBar(6);
console.log(bb.a); // 6(new > bind)

8. 硬绑定实现原理

手写 bind 实现

// 代码示例 10:完整的 bind polyfill
Function.prototype.myBind = function(thisArg, ...boundArgs) {
  if (typeof this !== 'function') {
    throw new TypeError('Bind must be called on a function');
  }
  
  const targetFn = this;
  const fNOP = function() {}; // 中间原型
  
  const boundFn = function(...callArgs) {
    // 判断是否被 new 调用
    const isNew = this instanceof fNOP;
    return targetFn.apply(
      isNew ? this : thisArg,
      [...boundArgs, ...callArgs]
    );
  };
  
  // 维护原型链(支持 new)
  if (targetFn.prototype) {
    fNOP.prototype = targetFn.prototype;
  }
  boundFn.prototype = new fNOP();
  
  return boundFn;
};

// 验证
function Foo(x, y) {
  this.val = x + y;
}

const BoundFoo = Foo.myBind(null, 10);
const instance = new BoundFoo(20);
console.log(instance.val); // 30
console.log(instance instanceof Foo); // true

手写 call/apply

// 手写 call
Function.prototype.myCall = function(context, ...args) {
  context = context == null ? globalThis : Object(context);
  const key = Symbol('temp');
  context[key] = this;
  const result = context[key](...args);
  delete context[key];
  return result;
};

// 手写 apply
Function.prototype.myApply = function(context, args = []) {
  context = context == null ? globalThis : Object(context);
  const key = Symbol('temp');
  context[key] = this;
  const result = context[key](...args);
  delete context[key];
  return result;
};

9. 实战案例

实战案例 1:React 类组件中的 this 问题

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    
    // 方案1:构造函数中 bind
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    this.setState(prev => ({ count: prev.count + 1 }));
  }
  
  // 方案2:类字段 + 箭头函数(推荐)
  handleClickArrow = () => {
    this.setState(prev => ({ count: prev.count + 1 }));
  };
  
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.count}
      </button>
    );
  }
}

性能对比:

  • bind 方案:每个实例共享原型上的方法,bind 后的函数在堆上分配
  • 箭头函数方案:每个实例都有独立的函数副本,内存占用更大
  • 在大列表渲染场景中,bind 方案更优

实战案例 2:事件委托中的 this 管理

class EventBus {
  #handlers = new Map();
  
  on(event, handler, context) {
    if (!this.#handlers.has(event)) {
      this.#handlers.set(event, []);
    }
    this.#handlers.get(event).push({
      fn: handler,
      ctx: context || null
    });
  }
  
  emit(event, ...args) {
    const handlers = this.#handlers.get(event) || [];
    for (const { fn, ctx } of handlers) {
      fn.apply(ctx, args); // 使用存储的 context
    }
  }
  
  off(event, handler) {
    const handlers = this.#handlers.get(event);
    if (handlers) {
      const idx = handlers.findIndex(h => h.fn === handler);
      if (idx !== -1) handlers.splice(idx, 1);
    }
  }
}

实战案例 3:链式调用模式

class QueryBuilder {
  #conditions = [];
  #table = '';
  
  from(table) {
    this.#table = table;
    return this; // 返回 this 实现链式
  }
  
  where(condition) {
    this.#conditions.push(condition);
    return this;
  }
  
  build() {
    const where = this.#conditions.length
      ? ` WHERE ${this.#conditions.join(' AND ')}`
      : '';
    return `SELECT * FROM ${this.#table}${where}`;
  }
}

const sql = new QueryBuilder()
  .from('users')
  .where('age > 18')
  .where('active = true')
  .build();

console.log(sql);
// SELECT * FROM users WHERE age > 18 AND active = true

10. 深度追问

Q1:为什么 bind 后的函数再次 bind 无效?

因为 bind 创建的是一个 exotic object(§10.4.1.1),其 [[Call]] 内部方法固定了 [[BoundThis]]。再次 bind 只是在外层又包了一层,但最内层的 [[BoundThis]] 不变。

Q2:Reflect.apply vs Function.prototype.apply 的区别?

Reflect.apply 不会在 thisArg 为 null/undefined 时替换为全局对象(即使在非严格模式)。此外,如果目标不是函数,Reflect.apply 会抛出 TypeError,而不是在调用时才发现。

Q3:Class 中的方法默认为严格模式吗?

是的。ECMAScript 规范规定 class body 始终处于严格模式(§15.7.1),因此 class 中方法的默认绑定 this 为 undefined 而非 globalThis。


11. 总结表格

绑定规则条件this 值优先级
new 绑定new Foo()新创建的对象最高
显式绑定call/apply/bind指定的对象高
隐式绑定obj.method()obj中
默认绑定独立调用 foo()globalThis / undefined低
箭头函数定义时确定继承外层 thisN/A(词法)
场景推荐方案原因
事件处理器箭头函数 / bind避免隐式丢失
回调函数箭头函数简洁且安全
方法定义普通函数支持动态 this
工具函数箭头函数无 this 语义
构造函数class / function必须支持 new

下一篇:04. 原型链与对象血缘关系