[英]Why does this example of inheritance not work on my computer?
我有一些Java背景,但是现在我正尝试用JavaScript和HTML编写一些简单的游戏。 我正在努力了解OOP的工作原理,因为似乎存在创建对象的不同方法? 我写了引用朋友代码的代码段,但是控制台给了我“未捕获的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>
您需要this
传递给.call
。
function Bear() {
Animal.call(this);
}
另外,您的原型继承也不完整。
您的函数与this
有所不同-尝试使用apply
方法,这会使您更进一步,例如;
function Bear() {
Animal.apply(this);
}
在javascript中还有很多需要的东西,例如原型定义
您的Bear函数需要this
传递给Animal调用。
为了更好地了解javascript继承,您可以查看有关了解javascript继承的博客
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.