简体   繁体   English

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

[英]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. 我有一些Java背景,但是现在我正尝试用JavaScript和HTML编写一些简单的游戏。 I'm struggling to understand how OOP works because it seems like there are different ways of creating objects? 我正在努力了解OOP的工作原理,因为似乎存在创建对象的不同方法? I wrote this snippet referencing a friend's code but the console gives me "uncaught TypeError: Cannot set property 'roar' of undefined". 我写了引用朋友代码的代码段,但是控制台给了我“未捕获的TypeError:无法设置未定义的属性'roar'”。 Why does the code work for him but not for me? 为什么该代码对他有效,但对我无效? Is he running some kind of server side library? 他在运行某种服务器端库吗?

test.js: 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: 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 . 您需要this传递给.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; 您的函数与this有所不同-尝试使用apply方法,这会使您更进一步,例如;

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

There are a lot more in javascript which is needed, such as prototype definitions 在javascript中还有很多需要的东西,例如原型定义

your Bear function needs to pass this to Animal call. 您的Bear函数需要this传递给Animal调用。

To understand javascript inheritance better you can check out this blog on understanding javascript inheritance 为了更好地了解javascript继承,您可以查看有关了解javascript继承的博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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