1: // the original Animal class and sayName method
2: function Animal(name, numLegs) {
3: this.name = name;
4: this.numLegs = numLegs;
5: }
6: Animal.prototype.sayName = function() {
7: console.log("Hi my name is " + this.name);
8: };
9: // define a Penguin class
10: function Penguin(name){
11: this.name = name;
12: this.numLegs = 2;
13: }
14: // set its prototype to be a new instance of Animal
15: Penguin.prototype = new Animal();
Showing posts with label prototype. Show all posts
Showing posts with label prototype. Show all posts
JavaScript - Inheritance, inherit properties and methods from parent class
1.Penguin class will inherit properties and classes from Animal class
JavaScript - using prototype to create method for specific class
snoopy can also bark since the bark() method is created for Dog class.1: function Dog (breed) { 2: this.breed = breed; 3: }; 4: // here we make buddy and teach him how to bark 5: var buddy = new Dog("golden Retriever"); 6:Dog.prototype.bark= function() { 7: console.log("Woof"); 8: }; 9: buddy.bark(); 10: // here we make snoopy 11: var snoopy = new Dog("Beagle"); 12: /// this time it works! 13: snoopy.bark();
Subscribe to:
Posts (Atom)