JavaScript将类方法赋值给变量后无法访问this的问题
类方法赋值给变量后无法访问实例
this的问题解决 将类的方法赋值给变量(例如const func2 = this.play_1;)后,调用该变量时无法访问类实例的this属性,示例代码及运行报错如下:
示例代码
function play_1(message = "play_1") { console.log("GLOBAL FUNCTION:", message); } class Demo { constructor() { this.number = 10; } play_1(message = "class play_1") { console.log("CLASS FUNCTION:", this.number, message); } test_assign_function() { play_1("without this"); this.play_1("with this"); const func = play_1; func("WORKING - func message from class is global"); const func2 = this.play_1; func2("NOT WORKING - func message from class"); } } function test_assign_function_in_class() { cls = new Demo(); cls.test_assign_function("class message"); } test_assign_function_in_class();
运行报错
"S:\Program Files\nodejs\node.exe" S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js GLOBAL FUNCTION: without this CLASS FUNCTION: 10 with this GLOBAL FUNCTION: WORKING - func message from class is global S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js:11 console.log("CLASS FUNCTION:", this.number, message); ^ TypeError: Cannot read property 'number' of undefined at play_1 (S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js:11:41) at Demo.test_assign_function (S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js:23:5) at test_assign_function_in_class (S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js:29:7) at Object.<anonymous> (S:\!kyxa\!code\play_chrome_cdp\nodejs_1\!play\assing_function.js:32:1) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47
问题原因
JavaScript中this的绑定是动态的,类的普通方法默认没有固定绑定this。当你把this.play_1赋值给变量func2后,方法脱离了类实例的上下文,调用func2时this会变成undefined(严格模式下),因此无法访问this.number。
解决方案
1. 使用bind强制绑定this
直接将方法与实例this绑定后再赋值:
const func2 = this.play_1.bind(this); func2("WORKING - func message from class");
2. 用箭头函数包裹调用
箭头函数的this遵循词法作用域,会继承当前上下文的this:
const func2 = (msg) => this.play_1(msg); func2("WORKING - func message from class");
3. 在构造函数中提前绑定方法
在类的构造函数里完成this绑定,后续所有调用该方法时this都指向实例:
class Demo { constructor() { this.number = 10; this.play_1 = this.play_1.bind(this); // 提前绑定 } // ...其他代码 }
4. 用类字段定义箭头函数(ES6+)
将类方法直接定义为箭头函数,这样this会永久绑定到类实例:
class Demo { constructor() { this.number = 10; } // 用类字段定义箭头函数 play_1 = (message = "class play_1") => { console.log("CLASS FUNCTION:", this.number, message); } // ...其他代码 }
内容的提问来源于stack exchange,提问作者SKulibin
相关产品推荐
相关产品推荐

