I want to assign variable to class function (like const func2 = this.play_1;
), but after that func2 has no access to this
property
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();
Get error:
"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