简体   繁体   中英

Why does this example of inheritance not work on my computer?

I have some Java background but now I am trying to write some simple games in JavaScript and HTML. I'm struggling to understand how OOP works because it seems like there are different ways of creating objects? I wrote this snippet referencing a friend's code but the console gives me "uncaught TypeError: Cannot set property 'roar' of undefined". Why does the code work for him but not for me? Is he running some kind of server side library?

test.js:

function Animal() {

    this.needsAir = true;

    this.roar = function() {

        console.log("roar");    

    }

}

function Bear() {

    Animal.call();

}

var init = function() {

    var bear = new Bear();
    bear.roar();
    console.log(bear.needsAir)

}

index.html:

<html>
    <head>
        <script type="text/javascript" src="./test.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            window.onload = function() {
                    init();
            }
        </script>
    </body>
</html>

You need to pass this to .call .

function Bear() {

    Animal.call(this);

}

Also, your prototype inheritance isn't complete as well.

Your functions have different this -- try to use the apply methods, which would get you somewhat further, like;

function Bear() {
    Animal.apply(this);
}

There are a lot more in javascript which is needed, such as prototype definitions

your Bear function needs to pass this to Animal call.

To understand javascript inheritance better you can check out this blog on understanding javascript inheritance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM