On May 29, 1:11 pm, Geoffrey Summerhayes <sumr...@gmail.comwrote:
So does method 2, but nastier:
var Animal={};
var Mouse=Animal;
var Cat=Animal;
Cat.Eats='mouses(sic)';
alert(Mouse.Eats); // ouch!
Yikes, ouch is right.
I found another method by more researching. It's using Crockford's
function for prototypical inheritance.
Object.prototype.clone = function() {
function TempClass() {};
TempClass.prototype = this;
return new TempClass();
}
Animal = {};
var Mouse = Animal.clone();
var Cat = Animal.clone();
Cat.eats = 'mouses';
alert(Mouse.eats); // Not ouch.
/* and using your example */
Animal.speak = function() { alert('*grim silence*'); };
var Mouse = Animal.clone();
Mouse.speak = function() { alert('squeak!'); };
var Cat = Animal.clone();
Cat.speak = function() { alert('hiss!'); };
var foo = Animal.clone();
var tom = Cat.clone();
var jerry = Mouse.clone();
var mortimer = Mouse.clone();
mortimer.speak = function() { alert("I can talk! Where's the
cheese?"); };
foo.speak();
tom.speak();
jerry.speak();
mortimer.speak();
I kind of like this method better. I guess I don't like that 'new'
keyword in JavaScript which makes me think that I'm not dealing with
objects like a true prototype-based language. It feels like I'm still
dealing with Classes.