Reputation: 11
I have some Java background but now I am trying to write some simple games in JavaScript and HTML. I'm struggling to understand how OOP works because it seems like there are different ways of creating objects? I wrote this snippet referencing a friend's code but the console gives me "uncaught TypeError: Cannot set property 'roar' of undefined". Why does the code work for him but not for me? Is he running some kind of server side library?
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>
Upvotes: 0
Views: 39
Reputation: 978
your Bear function needs to pass this
to Animal call.
To understand javascript inheritance better you can check out this blog on understanding javascript inheritance
Upvotes: 0
Reputation: 14688
Your functions have different this
-- try to use the apply
methods, which would get you somewhat further, like;
function Bear() {
Animal.apply(this);
}
There are a lot more in javascript which is needed, such as prototype definitions
Upvotes: 0
Reputation: 190941
You need to pass this
to .call
.
function Bear() {
Animal.call(this);
}
Also, your prototype inheritance isn't complete as well.
Upvotes: 6