JavaScript生成器函数中this绑定依赖调用上下文:直接调用时非严格模式为全局对象、严格模式为undefined;对象方法调用时指向该对象;可用call/apply/bind显式绑定。

在 JavaScript 生成器函数中,this 的绑定行为与普通函数一致,但因生成器的特殊执行机制(暂停/恢复),直接在 function* 内部访问 this 需要特别注意调用方式——生成器函数本身不绑定 this,它依赖于调用时的上下文;若未显式绑定,非严格模式下为全局对象,严格模式下为 undefined。
生成器函数默认不绑定 this
生成器函数是普通函数的一种,其 this 值由调用时的上下文决定,不会自动继承外层作用域或构造函数的 this:
- 直接调用
gen()→this是全局对象(非严格)或undefined(严格) - 通过对象方法调用
obj.gen()→this指向obj(前提是该方法是普通函数引用,而非箭头函数) - 使用
.call()、.apply()或.bind()可显式传入this
在对象方法中安全使用 this
若想在生成器中访问实例属性,应确保它作为对象方法被调用,并避免箭头函数包装(箭头函数不绑定 this):
class Counter {
constructor(value = 0) {
this.value = value;
}
// ✅ 正确:普通函数方法,this 指向实例
*countUp() {
while (true) {
yield this.value++;
}
}
}
const c = new Counter(10);
const it = c.countUp(); // this 正确指向 c
console.log(it.next().value); // 10
console.log(it.next().value); // 11
手动绑定 this 的场景
当需要将生成器函数单独提取并保持 this 时,可用 bind() 或闭包封装:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
立即学习“Java免费学习笔记(深入)”;
-
const iter = instance.gen.bind(instance)→ 返回一个绑定好this的生成器函数 - 或用普通函数包裹:
const iter = () => instance.gen(),但注意这会每次新建迭代器,不共享内部状态 - 避免:
const iter = () => instance.gen.call(null),这样会丢失this
不推荐:在生成器内部用箭头函数捕获 this
生成器函数体不能是箭头函数(语法错误),但有人误试图在内部用箭头函数“保存” this,这是多余且易错的:
*gen() {
const self = this; // ✅ 可读,但非必需
return {
next() { return { value: self.value++, done: false }; }
};
// ❌ 错误示例:*gen = () => { ... } 语法非法
真正需要的是确保调用时 this 正确,而不是在内部绕弯捕获。

















