判断顺序:函数种类 → 调用形式 → 模式与宿主
普通函数的 this 看调用方式;箭头函数沿词法环境取 this。不要只看定义在哪个对象里。下面的例子使用 ES 模块或严格模式,避免浏览器脚本与 Node.js 顶层行为混淆。
| 调用 | 普通函数的 this |
|---|---|
obj.method() |
obj |
f() |
严格函数为 undefined;非严格函数通常替换为所在领域的全局对象 |
f.call(x,a) / f.apply(x,[a]) |
严格函数收到 x;非严格函数会替换 null/undefined、包装原始值 |
f.bind(x) 后普通调用 |
绑定的 x |
new F() |
新创建的实例;F 必须可构造 |
方法脱离对象
javascript
"use strict";
const user = { name: "小林", read() { return this.name; } };
console.log(user.read()); // 小林
const read = user.read;
// read(); // TypeError,因为 this 是 undefined
console.log(read.call({ name: "小周" })); // 小周
console.log(read.bind(user)()); // 小林
函数并不记住“它曾经存在哪个属性上”。传 user.read 给其他函数时,最终的调用方式决定 this;定时器还涉及宿主约定,不能一律说 this 为 window 或 undefined。
箭头函数:用明确的外层 this 验证
javascript
function makeReader() {
return () => this.name;
}
const arrow = makeReader.call({ name: "外层" });
console.log(arrow.call({ name: "新对象" })); // 外层
const plus = (a, b) => a + b;
console.log(plus.bind(null, 2)(3)); // 5
call、apply、bind 不能改掉箭头函数的 this,但仍能传参;bind 仍能预设参数。对象字面量不会为箭头函数创造自己的 this。
bind 与 new 的边界
javascript
function Item(name) { this.name = name; }
const receiver = {};
const Bound = Item.bind(receiver, "书");
const item = new Bound();
console.log(item.name, receiver.name); // 书 undefined
console.log(item instanceof Item); // true
构造调用忽略绑定的 this,预设参数仍保留。不要把“bind 永久固定一切调用中的 this”当成规则。箭头函数不能用 new;并非所有普通写法的函数对象都可构造,例如简写方法也不支持 new。
环境表:只比较顶层
| 场景 | 顶层 this | 顶层 var |
|---|---|---|
| 浏览器经典 script | 通常为 window | 通常成为全局对象属性 |
ES 模块(浏览器或 Node .mjs) |
undefined | 模块作用域 |
Node CommonJS .cjs |
module.exports | 模块作用域 |
全局对象用 globalThis 引用。控制台的特殊求值行为不能代替文件中的运行规则。
自测
const x={n:2,f(){return this.n}}; const y={n:7,f:x.f}; y.f()返回什么?- 箭头函数
.bind(other,1)的哪一部分可能生效? - 为什么在模块顶层写
const f=()=>this.name; f()会报错? new Bound()会修改 receiver 吗?
解析
- 7,调用基值是 y。
- 参数预设有效,this 仍沿原有词法环境取得。
- 模块顶层 this 是 undefined,读取其 name 抛出 TypeError。
- 不会因绑定 this 而修改 receiver;构造时 this 是新实例。