Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Forked from jeremyckahn/inherit-by-proxy.js
Created November 11, 2013 22:30
Show Gist options
  • Select an option

  • Save xeoncross/7421682 to your computer and use it in GitHub Desktop.

Select an option

Save xeoncross/7421682 to your computer and use it in GitHub Desktop.
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
@xeoncross
Copy link
Copy Markdown
Author

var Parent = {
   // ...
};

var Child = Object.create(Parent);

var child = Object.create(Child);

console.log(Parent.isPrototypeOf(child)); // true
console.log(Child.isPrototypeOf(child)); // true

https://gist.github.com/jeremyckahn/5552373

@xeoncross
Copy link
Copy Markdown
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

http://stackoverflow.com/a/10430875/99923

@xeoncross
Copy link
Copy Markdown
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;
  }
});

JavaScript Inheritance Patterns

A collection of resources for learning JavaScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment