Last active
December 11, 2015 11:19
-
-
Save MarcelloDiSimone/4593226 to your computer and use it in GitHub Desktop.
A prototype inheritance helper
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
Prototyper = {}; | |
Prototyper.create = function (base) { | |
var empty = function () {}; | |
empty.prototype = base; | |
return new empty(); | |
}; | |
Prototyper.xtends = function (parent, instance) { | |
instance.prototype = this.create(parent.prototype); | |
instance.prototype.constructor = instance; | |
instance.prototype.__super__ = parent; | |
}; | |
var Car = function(){ | |
console.log("Car construct"); | |
}; | |
Car.prototype.drive = function () { | |
console.log("brumm"); | |
}; | |
var myCar = Prototyper.create(Car.prototype); | |
console.dir(myCar); | |
// What should work | |
var FourWheeler = function() { | |
this.__super__(); | |
console.log("FourWheeler construct"); | |
}; | |
Prototyper.xtends(Car, FourWheeler); | |
FourWheeler.prototype.driveOffroad = function () { | |
console.log("FourWheeler driveOffroad"); | |
} | |
var jeep = new FourWheeler(); | |
jeep.drive(); //brumm | |
jeep.driveOffroad(); //FourWheeler driveOffroad | |
console.log(jeep instanceof FourWheeler); // true | |
console.log(jeep instanceof Car); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment