Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a private field from a static method in javascript es6?

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?

like image 351
omega Avatar asked Sep 04 '25 16:09

omega


1 Answers

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.

like image 125
dlopez Avatar answered Sep 07 '25 17:09

dlopez