Skip to content

Instantly share code, notes, and snippets.

@elranu
Last active December 14, 2015 06:48
Show Gist options
  • Select an option

  • Save elranu/5045185 to your computer and use it in GitHub Desktop.

Select an option

Save elranu/5045185 to your computer and use it in GitHub Desktop.
inheritance in javascript
//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..."
//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