为什么这个继承示例在我的计算机上不起作用?

1 javascript oop inheritance

我有一些Java背景,但现在我正在尝试用JavaScript和HTML编写一些简单的游戏.我很难理解OOP是如何工作的,因为看起来有不同的创建对象的方法?我写了这个片段引用了朋友的代码,但是控制台给了我"未捕获的TypeError:无法设置未定义的属性'咆哮'".为什么代码适用于他而不适合我?他在运行某种服务器端库吗?

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)

}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Dan*_*ite 6

你需要传递this.call.

function Bear() {

    Animal.call(this);

}
Run Code Online (Sandbox Code Playgroud)

此外,您的原型继承也不完整.