对象方法被取出并作为普通回调调用时,不会自动记住原来的接收对象。可以用 method.bind(object) 创建绑定 this 的新函数,再把它作为回调传递。bind 不会立即执行方法;若后续要移除事件监听,应保存并复用同一个绑定函数引用。以下示例可在 node.js 18 中执行。

在严格模式下验证提取方法后 this 的变化
此例通过 assert.throws 捕获预期错误,不会让脚本因演示错误中途退出。执行 callback() 是普通函数调用;与 user.greet() 的调用形式不同,严格模式下它的 this 为 undefined。
'use strict';
const assert = require('node:assert/strict');
const user = {
name: 'Alice',
greet() { return `Hello, ${this.name}`; }
};
assert.equal(user.greet(), 'Hello, Alice');
const callback = user.greet;
assert.throws(() => callback(), TypeError);
const bound = user.greet.bind(user);
assert.equal(bound(), 'Hello, Alice');
console.log('提取方法与绑定回调检查通过');
其他 API 可能以自己的接收对象调用回调,不能把所有回调中的 this 都写成 undefined。需要保留业务对象时,应在传递方法时明确绑定,而不是依赖回调执行者的默认行为。

用 bind 返回函数,并与 call 的立即调用区分
bind 的后续参数可预先绑定一部分实参,调用时再补充剩余参数。call 则会立即执行原函数。对于普通调用,给绑定函数再使用 call 不会覆盖已经绑定的 this;本例不涉及构造调用或箭头函数。
'use strict';
const assert = require('node:assert/strict');
const account = {
prefix: 'A',
format(kind, id) { return `${this.prefix}:${kind}:${id}`; }
};
const callback = account.format.bind(account, 'order');
assert.equal(typeof callback, 'function');
assert.equal(callback(7), 'A:order:7');
assert.equal(callback.call({ prefix: 'B' }, 8), 'A:order:8');
assert.equal(account.format.call({ prefix: 'B' }, 'order', 9), 'B:order:9');
console.log('预设参数及调用方式检查通过');
箭头函数的 this 来自词法环境,不能用 bind 给它改成任意对象。若对象方法需要通过 this 读取对象字段,应先确认该方法本身采用适合的函数定义方式。
保存绑定函数引用,确保能够移除事件监听
下面用 Node.js 的 EventTarget 验证函数身份。每次 bind 都创建新函数,所以移除时重新 bind 会得到不同引用;保存的 handler 才是之前注册的同一个函数。浏览器 DOM 监听同样需要匹配监听函数及相应捕获选项。
'use strict';
const assert = require('node:assert/strict');
const counter = { calls: 0, onPing() { this.calls++; } };
const target = new EventTarget();
const handler = counter.onPing.bind(counter);
assert.notEqual(handler, counter.onPing.bind(counter));
target.addEventListener('ping', handler);
target.dispatchEvent(new Event('ping'));
assert.equal(counter.calls, 1);
target.removeEventListener('ping', handler);
target.dispatchEvent(new Event('ping'));
assert.equal(counter.calls, 1);
console.log('绑定函数身份与移除监听检查通过');
组件卸载时应使用保存的 handler 清理监听。反复创建绑定函数、重复注册却没有移除,可能导致一次事件调用多次;这与 this 是否正确是两个需要分别检查的问题。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











