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.
In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
3. The static Fields (or Class Variables) In Java, when we declare a field static, exactly a single copy of that field is created and shared among all instances of that class.
@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .
Yes. You can use the static method if it is declared as public : public static void f() { // ... }
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:
new
instanceSo 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()); } }
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