我有一些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)
你需要传递this给.call.
function Bear() {
Animal.call(this);
}
Run Code Online (Sandbox Code Playgroud)
此外,您的原型继承也不完整.
| 归档时间: |
|
| 查看次数: |
32 次 |
| 最近记录: |