调用Reflect.get时丢失this引用,如何修复函数的this绑定?
修复函数调用时丢失this引用的问题
你的问题核心是类方法被单独取出调用时,丢失了原本指向实例的this绑定。类的方法(比如create)内部的this默认指向类实例,但当你通过Reflect.get把函数从实例中取出后,直接调用时没有指定上下文,this会变为undefined(严格模式下),导致访问this.obj报错。
两种可行的修复方案:
方案1:使用bind永久绑定this
在返回函数前,用bind把函数的this固定为传入的实例对象,这样无论后续怎么调用,函数内部的this都会指向该实例:
const mapHandler = (str, obj) => { if (!Reflect.has(obj, str)) { return null; } const candidateHandler = Reflect.get(obj, str, obj); if (typeof candidateHandler !== "function") { return null; } // 绑定this到目标实例 return candidateHandler.bind(obj); };
方案2:用箭头函数包裹,调用时指定上下文
返回一个箭头函数,内部通过call指定调用上下文为实例,也能保证this的正确指向:
const mapHandler = (str, obj) => { if (!Reflect.has(obj, str)) { return null; } const candidateHandler = Reflect.get(obj, str, obj); if (typeof candidateHandler !== "function") { return null; } // 箭头函数无自身this,调用时通过call指定实例上下文 return () => candidateHandler.call(obj); };
验证修复效果
修改后执行你的调用代码:
const myobj = new MyClass(); const handler = mapHandler("create", myobj); console.log("Found", handler); // Found [Function: create](或绑定后的函数) const res = handler(); console.log(res); // 输出1,不再报错
内容的提问来源于stack exchange,提问作者Andry
相关产品推荐
相关产品推荐

