-
-
Save xeoncross/7421682 to your computer and use it in GitHub Desktop.
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
| function inherit (child, parent) { | |
| function proxy () {}; | |
| proxy.prototype = parent.prototype; | |
| child.prototype = new proxy(); | |
| }; | |
| function Parent () {} | |
| function Child () {} | |
| inherit(Child, Parent); | |
| var child = new Child(); | |
| console.log(child instanceof Child); // true | |
| console.log(child instanceof Parent); // true |
Author
Author
Actually, the non-ES5 polyfilly for Object.create() is:
Object.create = function(o) {
function F(){}
F.prototype = o;
return new F();
};
Author
var Person = function(name){
this.name = name;
this.type = 'human';
}
Person.prototype.info = function(){
console.log("Name:", this.name, "Type:", this.type);
}
var Robot = function(name){
this.name = name;
this.type = 'robot';
}
Robot.prototype = new Person(); // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot
person = new Person("Bob");
robot = new Robot("Boutros");
person.info();
// Name: Bob Type: human
robot.info();
// Name: Boutros Type: robot
Author
The world's smallest and fastest classical JavaScript inheritance pattern.
If you'd like a safe, small and fast function for conveniently setting up the prototype chain (a.k.a. classical inheritance in JavaScript), that works cross-browser, try this one on for size:
function augment(parent, properties) {
var child = properties.constructor || function() {
return parent.apply(this, arguments);
};
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
for (var key in properties) {
child.prototype[key] = properties[key];
}
return child;
};
... the nasty bit of JavaScript-specific business there being the intermediate Surrogate, so that you don't need a concrete instance of the parent class to be instantiated, in order to set your prototype chain. Used like so:
var Person = augment(Model, {
sortableName: function() {
return this.lastName + ', ' + this.firstName;
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/jeremyckahn/5552373