Search code examples
subclassderived-class

JavaScript -Creating derived class


<html><head><script>
function Pet(){                                        // Base Class
    var owner = "Mrs. Jones";
    var gender = undefined;
    this.setOwner = function(who) { owner=who; };        //1
    this.getOwner = function(){ return owner; }
    this.setGender = function(sex) { gender=sex; }
    this.getGender = function(){ return gender; }
}

function Cat(){}                                       //subclass constructor
Cat.prototype = new Pet();  
Cat.prototype.constructor=Cat;
Cat.prototype.speak=function speak(){
    return("Meow");                                      //2
    };                                                   //3

function Dog(){};                                        //4     
Dog.prototype= new Pet();
Dog.prototype.constructor=Dog;
Dog.prototype.speak = function speak(){
    return("Woof");
    };                                                   //5

</script></head>
<body><script>

var cat = new Cat;
var dog = new Dog;
cat.setOwner("John Doe");
cat.setGender("Female");
dog.setGender("Male");
document.write(
     "<br>The cat is a "+ cat.getGender()+ " owned by "
     + cat.getOwner() +" and it says " + cat.speak());
document.write(
    "<br>The dog is a "+ dog.getGender() + " "
    + " owned by " + dog.getOwner() + " and it says " + dog.speak());
</script></body>
  1. Why are there semicolons after the closing curly braces in the above code at lines marked //1, //2, //3, //4 and //5 ?
  2. When will Cat.prototype = new Pet(); and Dog.prototype = new Pet(); be executed.

Solution

  • Well... JavaScript won't put semicolons anywhere in your code on its own, the person who wrote the script did that, right? What JavaScript does though, is auto inserting semicolons in spaces you missed (not in your code, not visibly at least. It reads your code and then it behaves as if you had those auto inserted semicolons there when you wrote it). This can sometimes produce unexpected results.

    I suggest using semicolons after each statement, as noted in this great article.

    If I understand your second question correctly, then it goes like this:
    Javascript instantiates new Object based on object Pet's prototype. Then points Cat.prototype to this newly created object. Same thing happens in case of Dog.