AS1 OOP: Custom Classes with MovieClips
by senocular
The Init Method
There is another alternative to using the init object as a
means of providing your class constructor with variable
arguments. That alternative is to essentially not use the
constructor at all and instead opt to construct or initiate
your object through, not the constructor, but a separate
method call directly following attachMovie. This method is
often called the init method.
The init method for movieclip classes are methods but
take on the responsibilities of constructor functions. It
not only allows you to have a constructor-like operation
with optional passed parameters, but also gives you a way to
re-construct or re-initialize an object through a method, as
though redefining an instance from scratch. That alone may
be reason enough to use this technique with other classes as
well.
As a method, though, init will need to be called
manually, adding what otherwise would be an extra step in
movieclip creation. We can see its use by incorporating it
into the Helper example.
- Helper = function(){
- // constructor not used in favor of init
- };
- Helper.prototype = new MovieClip();
- Helper.prototype.init = function(status){
- if (status == "inactive"){
- this._alpha = 50;
- }
- };
- Object.registerClass("helperClip", Helper);
- screenStatus = "inactive";
- this.attachMovie("helperClip", "helper1", 1);
- helper1.init(screenStatus);
- trace(helper1._alpha); // traces 50
The constructor is still run – its run automatically –
but it has no purpose now. The constructor responsibilities
are carried over to the init method. Being a method called
after the creation of the object, it can have any argument
passed to it you wish just as though it were any other
constructor call.
If you want, you can even compact its use a little by
tacking init right on the end of the attachMovie call. In
doing this, just be sure to return this in the init call so
that you are still able to assign variables to reference the
movieclip in the call.
- Helper = function(){};
- Helper.prototype = new MovieClip();
- Helper.prototype.init = function(status){
- if (status == "inactive"){
- this._alpha = 50;
- }
- return this;
- };
- Object.registerClass("helperClip", Helper);
- screenStatus = "inactive";
- this.attachMovie("helperClip", "helper1", 1).init(screenStatus);