为什么这个继承的例子不能在我的计算机上工作?

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

本文关键字:我的 计算机 工作 不能 继承 为什么      更新时间:2023-09-26

我有一些Java背景,但现在我正试图用JavaScript和HTML编写一些简单的游戏。我正在努力理解OOP是如何工作的,因为它似乎有不同的方式来创建对象?我写的这段代码引用了一个朋友的代码,但是控制台给了我"未捕获的TypeError: Cannot set property 'roar' of undefined"。为什么代码对他有用,对我没用?他在运行什么服务器端库吗?

. 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>

您需要将this传递给.call

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

同样,你的原型继承也不完整。

您的函数具有不同的this—尝试使用apply方法,这将使您更进一步,如;

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

javascript中还有很多需要的东西,比如原型定义

Bear函数需要将this传递给Animal call。

为了更好地理解javascript继承,你可以查看这个博客