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(); 

http://jsfiddle.net/dgcoffman/mguua/5/

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

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -