Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

actionscript 3 - Don't I have to call super() in constructor when class extends Sprite in actionscript3?

I always don't call super() when I extends Sprite.
But doesn't not calling super() cause any problem?

Till now, I don't have any problem and I have never seen code which call super() in constructor which class extends Sprite.

How about TextField?
I don't have any problem about TextField, too.

How to know whether I should call super() or not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If flash doesn't detect a call to super() in your child constructor then flash will implicitly call super() before your child's constructor. So:

public class Parent {
    public function Parent() {
        trace("Parent");
    }
}

public class Child extends Parent {
    public function Child() {
        trace("Child");
    }
}

new Child();
// Parent
// Child

So your child constructor essentially looks like this

    public function Child() {
        super(); // <-- Added by flash! 
        trace("Child");
    }

So, no, omitting an explicit call to super() will not usually adversely affect your child's class.

So why would you want to explicitly call super()?

The first reason is flash will only ever automatically generate a parameterless call to super, meaning that if your parent classes constructor requires arguments, then you will need to explicitly call it with those arguments. If you omit the super(args...) call in this case, you will get a compiler error.

Second, if even your parent has a parameter-less constructor, you can use super() to control the order that the constructors execute. Flash will always insert the call before the childs constructor. So if you wanted to change that order. Then

public class Child extends Parent {
    public function Child() {
        trace("Child");
        super()
    }
}

would do it in the opposite order. Or you could do:

public class Child extends Parent {
    public function Child() {
        // work before initilizing parent 
        super()
        // work after initilizing parent
    }
}

Lastly, there is a very obscure way to not call your parents constructor by saying:

public class Child extends Parent {
    public function Child() {
        if(false) super()
    }
}

Because flash sees there is a call, it doesn't insert one. However because its behind a if (false) it never gets called, so the parent class never gets initialized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...