JavaScript:类实例方法传入函数后this为undefined的解决办法
解决
this绑定丢失的问题 当你直接把类实例的方法t.test作为参数传递给myFunc时,方法的this绑定会丢失——调用f()时,this在严格模式下是undefined,自然无法访问this.potato。以下是三种常见的解决方式:
1. 使用bind固定this
bind方法会创建一个新函数,强制将其this绑定到指定的实例对象,无论后续如何调用这个新函数,this都不会改变。
function myFunc(f) { console.log(f()); } class Test { potato = "potato"; test() { return this.potato; } } const t = new Test(); myFunc(t.test.bind(t));
2. 用箭头函数包裹调用
箭头函数的this继承自外层作用域,这里直接在箭头函数中调用t.test(),确保test方法执行时的this指向实例t。
function myFunc(f) { console.log(f()); } class Test { potato = "potato"; test() { return this.potato; } } const t = new Test(); myFunc(() => t.test());
3. 将类方法定义为箭头函数
在类字段中用箭头函数定义方法,这样方法会捕获类实例的this,后续无论怎么传递这个方法的引用,this始终指向实例本身。
function myFunc(f) { console.log(f()); } class Test { potato = "potato"; test = () => { return this.potato; } } const t = new Test(); myFunc(t.test);
注意:第三种方式会让每个类实例都持有一份
test函数的副本,相比原型链上的方法会占用更多内存,适合小场景使用。
内容的提问来源于stack exchange,提问作者Ahmet Yazıcı
相关产品推荐
相关产品推荐

