From e6620b104d5349c1ccdc26508d5df8f8ae7401b6 Mon Sep 17 00:00:00 2001 From: Kyle K Date: Wed, 1 Mar 2017 22:47:47 -0600 Subject: example of inheritance in JS --- inheritance.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 inheritance.js diff --git a/inheritance.js b/inheritance.js new file mode 100644 index 0000000..2fab447 --- /dev/null +++ b/inheritance.js @@ -0,0 +1,29 @@ +function Person(name){ + this.name = name; + this.type = 'human'; + this.info = function() { + console.log("Name:", this.name, "Type:", this.type); + } +} +Person.prototype.roboinfo = function(){ + console.log("Name:", this.name, "Type:", this.type, "Processor:", this.cpu); +} + +function Robot(name){ + Person.call(this, name) // akin of calling super, this is what allows us to inherit props + this.type = 'robot'; + this.cpu = 'AMD64' +} + +// Set Robot's prototype to Person's prototype +Robot.prototype = Person.prototype; + +// Set constructor back to Robot +Robot.prototype.constructor = Robot; + +person = new Person("Bob"); +robot = new Robot("Bender"); + +person.info(); // Name: Bob Type: human +robot.info(); // Name: Bender Type: robot +robot.roboinfo(); // Name: Bender Type: robot Processor: AMD64 \ No newline at end of file -- cgit v1.2.3