PDA

View Full Version : What is the difference between static and instance methods in Actionscript 3.0?



fs_tigre
January 2nd, 2010, 12:55 PM
Hi,

Asking a question here in this forum someone from here suggested me to changed one of my methods to static and it worked for what I was trying to do but I would like to know what is the difference between static and instance method.

What is the difference between static and instance methods?

Can someone be so kind and explain this a little bit?

Thanks a lot!

wvxvw
January 2nd, 2010, 01:45 PM
Consider this:
A is a class.
A has static method sm and instance method im.
then, if you create a new insance of A, let's call it a the following will be true:


A.sm != null;
A.im == null;
a.sm == null;
a.im != null;

If class A isn't dynamic, then when you try to access a method that isn't an instance method of the class A you will get an error (NPE - null pointer exception).

In other words, instance method are copied into every new instance, while static methods belong to the class itself. Thus, if you create 2 instances of class A, you will duplicate the im method, however, sm method will not be duplicated.
Static methods are also different from instance method in that they don't have a default scope - that is this keyword has no meaning for them. This also means that internally, static methods aren't the same entities as instance methods (since the implementation of the instance method in AS3 requires it to have a default scope).
Considering speed: accessing static methods is slightly slower then accessing instance method in case there are many static methods. (Since dynamic access is slower in general).

However, Class class is dynamic, so, instances of Class (A for example) will not give you an error if you will try to access a non-existent property on them.

fs_tigre
January 2nd, 2010, 02:23 PM
In other words, instance method are copied into every new instance, while static methods belong to the class itself.

So, this means that with instance methods you have full access to the method at self when you create new instances of the class and not with static methods.

Thanks

wvxvw
January 2nd, 2010, 03:32 PM
It is a bit more complex then this, but, in general - yes. (However, there are namespaces that define what may or may not be accessed - example, if you put a method into internal namespace, and then extend that class in another package, and then try to access the internal method from another method of that class - you wouldn't be able to).

fs_tigre
January 2nd, 2010, 08:07 PM
Thanks a lot!