Trying to understand inheritance in JavaScript -- what's going on here? -
why "animal" instead of "kitty"?
// create base class animal function animal(animaltype) { this.type = animaltype; this.saytype = function () { alert(this.type); }; } // create derived class cat function cat(myname) { animal.call(this, "cat"); // cat calls animal base class constructor this.name = myname; this.sayname = function () { alert(this.name); }; } cat.prototype = object.create(animal); // set cat's prototype animal // instantiate new instance of cat var cat = new cat("kitty"); cat.sayname(); cat.name = "lol"; cat.sayname();
object.create(animal); // set cat's prototype animal
yes, animal
constructor function (or, exact: new object inheriting function object - check docs object.create
). that's hardly want - , explains curious result of saying "animal"
, that's animal
function's name
property.
instead, want build prototype chain, cat instances inherit cat.prototype
inherits animal.prototype
(which inherits object.prototype
):
cat.prototype = object.create(animal.prototype);
also, prototypical inheritance, should sayname
, saytype
methods on prototype object (and once):
animal.prototype.saytype = function() { alert(this.type); }; cat.prototype.sayname = function() { // after creation of object, of course alert(this.name); };
Comments
Post a Comment