Invoking private method from static method ES6 - javascript

I am unable to call private or non static method from static method in class, below is the example
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.fun1();
}
}
a.staticfun();
I am trying to expose only staticfun method which internally calls all private methods, but this gives me this.fun1 is not a function. I tried to find many ways to find it with 'this', but it does work.
How do I call private instance methods inside static methods?

fun1 is not a static function, so you need to define a new instance of the a class in order to call it:
class a {
fun1() {
console.log('fun1');
}
static staticfun() {
console.log('staticfun');
new this().fun1();
}
}
a.staticfun();
You should note that this is not good practice, though. You shouldn't have a static method relying on non-static logic.
A workaround would be to pass an instance of a to the static function, but that completely defies the point of having a static method in the first place.

Another way is to call the function directly from the class prototype (meaning literally the prototype property, not __proto__), if you want to avoid instantiating it.
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.prototype.fun1();
}
}
a.staticfun();

First, read this SO question
It's possible, You can create an instance of class a and then invoke from the instance the method fun1.
Although, There is no sense to call a non-static method from a static one.
static means that this method belong to the object (not to the instance)
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
const classInstance = new a()
classInstance.fun1();
}
}
a.staticfun();

Related

What does the `#` symbol do in JavaScript?

I encountered code that contained the # sign. What is it used for? The code looks something like this:
class someObject{
#someMethod(){
//do something
}
}
It's a sigil (rather than an operator) that indicates that the member is private — in this case, a private method, but it's also used for private fields.
You can't use a private method or private field in code outside the class declaring them. For instance:
class Example {
doSomething() {
this.#method("from doSomething"); // <== Works
}
#method(str) {
console.log("method called: " + str);
}
}
const e = new Example();
e.doSomething();
e.#method(); // <=== FAILS
This is an experimental proposal. You can define Private JavaScript methods Using #
For more info, you can refer to the MDN docs
Class properties are public by default and can be examined or modified outside the class. There is however an experimental proposal to allow defining private class fields using a hash # prefix.
You can achieve something similar using ES5 (just for the sake of simplicity to explain), where you can simulate something like Private methods (which JavaScript doesn't have one natively.)
For example:
function someObj() { //assuming this is a class definition
function someMethod() { //private method which is not accessible outside someObj
}
function init() { //initializes some methods or code, private methods can be used here
someMethod();
}
return {
init //only exposes the init method outside
}
}
In the above, it will only expose the init method from the someObj which can be called as someObj.init(), whereas your someMethod will not be accessible outside of its parent method.
Example:
someObj.init(); //works
someObj.someMethod(); //won't be accessible
hash is used to define private class fields

Any striking difference between class/instance methods vs static methods for use in applications?

I am building APIs for an application. I want to know if there is any difference between writing the functionality methods as this:
class Foo {
static method1(req, res) {}
static method2(req, res) {}
}
and
class Foo {
method1(req, res) {}
method2(req, res) {}
}
I know static methods are made directly on the class and are not callable on instances of the class and they are often used to create utility functions but I just want to know if there is a disadvantage or any effect if static is not added while creating the functionalities for the application.
If static is not added, then the method can only be called on an instance of the object.
If static is added, then the method can only be called with the class name prefix, not an instance of the object.
If you have a method that could be static (does not reference any instance data or use this to refer to an object instance), then you can make it either static or not static. If you make it non-static, it will still work just fine, but it will only be callable on an instance of the object itself or with a direct reference to Foo.prototype.method().
So, the disadvantage of not making a static method actually be declared static is that it's not as clean to use it when you don't have an instance of the object around. That's what static methods were invented for - to make it clean to declare and use functions namespaced to your class that don't require an instance.

How can I access the inherited static property from the inherited static method? [duplicate]

I have this class which does an internal call to a static method:
export class GeneralHelper extends BaseHelper{
static is(env){
return config.get('env:name') === env;
}
static isProd(){
return GeneralHelper.is('prod');
}
}
Are there any keywords I can use to replace the class name in the line below:
GeneralHelper.is('prod');
In PHP there are self, static etc. Does ES6 provide anything similar to these?
TY.
If you are calling the static function from inside an instance, the right way to refer to the static function of the class is:
this.constructor.functionName();
Call static methods from regular ES6 class methods
It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd() method, the GeneralHelper will be available as this in the method, so you can use
class GeneralHelper {
static is(env) { … }
static isProd(){
return this.is('prod');
}
}
This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper explicitly when someone inherits isProd from your class and overwrites is, InheritedHelper.isProd() will produce other results.
If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.
Both of the answers here are correct and good, but I wanted to throw in an added detail based on this question title.
When I saw "ES6 - Call static method within a class" it sounded like "call a static method (from a non-static method) within a class". Def not what the initial question asker is asking in the details.
But for anyone who wants to know how to call a static method from a non-static method within a class you can do it like this:
class MyClass {
myNonStaticMethod () {
console.log("I'm not static.")
MyClass.myStaticMethod()
}
static myStaticMethod () {
console.log("hey, I'm static!")
}
}
MyClass.myStaticMethod() // will log "hey, I'm static!"
const me = new MyClass()
me.myNonStaticMethod() // will log "I'm not static" and then "hey, I'm static!"
The idea is that the static method is can be called without creating a new instance of the class. That means you can call it inside of a instance's method the same way you'd call it outside of the instance.
Again, I know that's not what the detail of the question was asking for, but this could be helpful other people.

ES6 - Call static method within a class

I have this class which does an internal call to a static method:
export class GeneralHelper extends BaseHelper{
static is(env){
return config.get('env:name') === env;
}
static isProd(){
return GeneralHelper.is('prod');
}
}
Are there any keywords I can use to replace the class name in the line below:
GeneralHelper.is('prod');
In PHP there are self, static etc. Does ES6 provide anything similar to these?
TY.
If you are calling the static function from inside an instance, the right way to refer to the static function of the class is:
this.constructor.functionName();
Call static methods from regular ES6 class methods
It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd() method, the GeneralHelper will be available as this in the method, so you can use
class GeneralHelper {
static is(env) { … }
static isProd(){
return this.is('prod');
}
}
This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper explicitly when someone inherits isProd from your class and overwrites is, InheritedHelper.isProd() will produce other results.
If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.
Both of the answers here are correct and good, but I wanted to throw in an added detail based on this question title.
When I saw "ES6 - Call static method within a class" it sounded like "call a static method (from a non-static method) within a class". Def not what the initial question asker is asking in the details.
But for anyone who wants to know how to call a static method from a non-static method within a class you can do it like this:
class MyClass {
myNonStaticMethod () {
console.log("I'm not static.")
MyClass.myStaticMethod()
}
static myStaticMethod () {
console.log("hey, I'm static!")
}
}
MyClass.myStaticMethod() // will log "hey, I'm static!"
const me = new MyClass()
me.myNonStaticMethod() // will log "I'm not static" and then "hey, I'm static!"
The idea is that the static method is can be called without creating a new instance of the class. That means you can call it inside of a instance's method the same way you'd call it outside of the instance.
Again, I know that's not what the detail of the question was asking for, but this could be helpful other people.

TypeScript: Access static methods within classes (the same or another ones)

Suppose we have the following code:
[Test.js file]:
class Test {
...
public static aStaticFunction():void {
...
this.aMemberFunction(); // <- Issue #1.
}
private aMemberFunction():void {
...
this.aStaticFunction(); // <- Issue #2.
}
}
[Another.js file]:
class Another {
...
private anotherMemberFunction():void {
Test.aStaticFunction(); // <- Issue #3.
}
}
See the Issue #x. comments for the issues (3) I want to address.
I've been playing with some configurations by now and I don't get it all yet.
Can you help me to understand how can I access this methods in the three places?
Thanks.
There is some code below, but there are some important concepts to bear in mind.
A static method does not exist on any instance. There are good reasons for this:
It can be called before you have created a new instance
It can be called from outside an instance, so you wouldn't know which instance the call was related to
So in all cases where you call the static method, you need to use the full name:
Test.aStaticFunction();
If the static method needs to call an instance method, you need to pass that in. This does set off alarm bells for me though. If the static method depends on an instance method, it probably shouldn't be a static method.
To see what I mean, think about this problem.
If I call Test.aStaticFunction() from outside of an instance, when 100 instances have been created, which instance should the static function use? There is no way of telling. If your method needs to know data from the instance or call methods on the instance, it almost certainly shouldn't be static.
So although the code below works, it probably isn't really what you require - what you probably need is to remove the static keyword and make sure you have an instance to call in your other classes.
interface IHasMemberFunction {
aMemberFunction(): void;
}
class Test {
public static aStaticFunction(aClass: IHasMemberFunction):void {
aClass.aMemberFunction();
}
private aMemberFunction():void {
Test.aStaticFunction(this);
}
}
class Another {
private anotherMemberFunction():void {
Test.aStaticFunction(new Test());
}
}
this is related to an instance whereas static members are independent of any instance. So if you want to access members of an instance within a static member you have to pass it in. However in that case I don't see a reason for having a static member in the first place. I believe you need two functions. one static and one non-static. That do two different things, so :
class Test {
public notaStaticFunction():void {
this.aMemberFunction(); // <- Issue #1.
}
public static aStaticFunction():void {
}
private aMemberFunction():void {
this.notaStaticFunction(); // <- Issue #2.
}
}
class Another {
private anotherMemberFunction():void {
Test.aStaticFunction(); // <- Issue #3.
}
}
That said you can share properties between static and member functions using static properties.
dont use class name like Class.staticMethod(), use this:
this.constructor.staticMethod()
to maintain the inheritance of static methods
Edit: as mentioned in comments, typescript does not support this.constructor. There is an open ticket in it's issue tracker, but not much progress over last 5 years.

Categories