Last active
December 14, 2015 06:48
-
-
Save elranu/5045185 to your computer and use it in GitHub Desktop.
inheritance in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //More info: http://javascript.crockford.com/private.html | |
| function Vehicle() { | |
| this.pepe = function(){ | |
| console.log('pepe'); | |
| }; | |
| } | |
| Vehicle.prototype.drive = function () { | |
| console.log("vrooom..."); | |
| } | |
| function Car() { | |
| } | |
| Car.prototype = new Vehicle(); | |
| Car.prototype.honk = function() { | |
| console.log("honk honk"); | |
| this.pepe(); | |
| } | |
| var myCar = new Car(); | |
| myCar.honk(); // outputs "honk honk" "pepe" | |
| myCar.drive(); // outputs "vrooom..." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Object composition example | |
| function getVehicle() { | |
| var obj = {}; | |
| obj.pepe = function(){ | |
| console.log('pepe'); | |
| }; | |
| obj.drive = function () { | |
| console.log("vrooom..."); | |
| }; | |
| return obj; | |
| } | |
| function getCar(vehicle){ | |
| vehicle.honk = function() { | |
| console.log("honk honk"); | |
| vehicle.pepe(); | |
| }; | |
| return vehicle; | |
| } | |
| var myCar = getCar(getVehicle()); | |
| myCar.honk(); // outputs "honk honk" "pepe" | |
| myCar.drive(); // outputs "vrooom..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment