【问题标题】:Why does this example of inheritance not work on my computer?为什么这个继承示例在我的计算机上不起作用?
【发布时间】:2015-09-04 00:17:50
【问题描述】:

我有一些 Java 背景,但现在我正在尝试用 JavaScript 和 HTML 编写一些简单的游戏。我很难理解 OOP 是如何工作的,因为似乎有不同的创建对象的方式?我写了这个 sn-p 引用朋友的代码,但控制台给了我“未捕获的 TypeError:无法设置未定义的属性 'roar'”。为什么代码对他有用,但对我不起作用?他在运行某种服务器端库吗?

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>

【问题讨论】:

  • 首先,Bear的this和Animal的this是两个不同的对象

标签: javascript oop inheritance


【解决方案1】:

您需要将this 传递给.call

function Bear() {

    Animal.call(this);

}

另外,您的原型继承也不完整。

【讨论】:

    【解决方案2】:

    你的函数有不同的this -- 尝试使用apply 方法,这会让你更进一步,比如;

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

    在 javascript 中还有很多需要,例如原型定义

    【讨论】:

      【解决方案3】:

      您的 Bear 函数需要将 this 传递给 Animal 调用。

      要更好地理解 javascript 继承,您可以查看blog on understanding javascript inheritance

      【讨论】:

      • 谢谢,您的链接很有帮助。
      猜你喜欢
      • 2016-04-18
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2018-06-12
      • 2014-06-22
      • 1970-01-01
      相关资源
      最近更新 更多