OK I’ve got some question about what I guess is basic OOP. For example, let’s say I have many diffrent objects which has diffrent classes. Let’s say, one object called, car (Car.as), then I have a truck (truck.as) and a moped (moped.as). Now instead of writing a simple function within all of these, can’t I have a class and then attach this function onto everyone of these objects?
For example I want them to be able to fade out. Then I have a class called “AlphaThings” and within this class I write a simple fadeout function.
Can’t I somehow then attach this function to another object? Like
AlphaThings.fadeout(car);
AlphaThings.fadeout(truck);
AlphaThings.fadein(moped);
Thanks, and sorry if there some misspelled words.
You’re trying to accomplish inheritance, which is where a class inherits properties and methods from another.
Inheritance is accomplished by using the
extendskeyword when defining the class.Your three objects
Car,TruckandMopedcould inherit from (extend)AlphaThingslike this:Your
Carwill now contain all of the properties and methods defined withinAlphaThings, such as.fadein()and.fadeout()that you mentioned.Bonus info:
When you extend another class, you can alter how methods existing within the base class will work in the class inheriting from it. This is done using the
overridekeyword.For example, you may want your
Carto do something slightly different or additional when you use.fadein()on it, so you would override that method like this:The line
super.fadein()is there to call the original.fadein()function. If you omit this, you can completely rewrite the function and have the previously defined actions ignored.Regarding this specific scenario:
This answer of course gets straight to the point and answers the question directly by explaining how to achieve inheritance. With that said, what you’re trying to achieve can be done more cleanly using one of a handful of other routes.
For example, consider this Tweening Library by Greensock. The library can deal with the transitioning of any values (including alpha) on any objects in different ways. Here are some examples of why this is great vs using inheritance:
AlphaThingsfrom your example to use it.AlphaThingsin a new project.