I am looking to make a function that is both private and static in javascript. Is there a way to do it?
I know by doing
#myfunc = function() {
}
I can make it private. But when I try to access that from a function marked as static, I get
(node:15092) UnhandledPromiseRejectionWarning: TypeError: Cannot read private member #myfunc from an object whose class did not declare it
How can I fix it?
As far as I know, you can't define private static methods with the current ecmascript version. But you can emulate an static method by declaring a function outside the class but within the same file.
While you don't export that function from that file, it will work the same way as a private static method, but the way of calling it.
It's a way to achieve the same behaviour with the current javascript specification.
// MyFile.js
function myPrivateMethod() {} // You won't have access to this function outside this file
export class MyClass {
myMethod() {
myPrivateMethod();
}
}
If you want to access static properties, you just need to call MyClass.myStaticProperty. In that case I suggest you to define the function after the class definition, to avoid hoisting issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With