I need to create a main class animal
, then have two sub classes inherit properties from animal
which are cat
and dog
, then I was to make multiple objects (multiple cat's and dog's) inherit from the class cat
and dog
(I read it's not really a class but it behaves as a class).
The multiple objects (cat1, mycat, tomcat, dog1, mydog, topdog) need to be able to talk and listen to each other. When talking I would have them just alert or print a text line. What I am having trouble with is the listening part. I want the individual myDog to print out "dog heard cat" when myCat makes a sound. This is the code I have so far.
var animal = function (name, sound, listen) {
var f = 0;
this.name = name; // this.prop means prop is public var.
this.sound = sound;
this.listen = listen;
this.makesound = function () {
alert(this.sound);
}
this.listen = function () {
alert(this.name + "heard that");
}
return this;
};
/*--------------- inheritance -----------------------------------*/
var cat = function () {
this.name = name;
this.sound = 'meow';
return this;
};
cat.prototype = new animal();
function dog(name) {
dog.sound = 'woof';
dog.name = name;
return this;
};
dog.prototype = new animal();
/*-------- different kinda dogs/cats ----------------------------*/
var myCat = new cat();
var myDog = new dog();
var tomCat = new cat();
var bigDog = new dog();
/*-----------------------*/
I think I'm supposed to use an if
statement, I heard I can use like a
if (callback) callback{}
but my attempts to implement something like that are failing. I'm BRAND new to javascript only been learning it last couple days. Any help or assistance would be really appreciated.
There is a pattern for that, the Observer pattern. When an animal makes a sound the other animals get notified (they 'listen' to it).
So the
makeSound
function has to call thelisten
method of all animals that can 'listen' to the sound. To do that it has to know those, i.e. have a list of them, or if it's only one, have a reference to that.listening
could come in as an argument via constructor or method.P.S.: Never use an
if
orswitch
to make decisions based on a type. That's what OOP is for.This is how I would do it... I'd set those who are listening.
listening
is an optional parameter when you create a new object. You can also change those who are listening after creation usingsetListening
.listening
in this case will just be an array of objects that have aname
property.Also, I fixed some issues, you either didn't have "name" or weren't setting it in any case.
http://jsfiddle.net/n9xCM/