Skip to content

Instantly share code, notes, and snippets.

@RinatMullayanov
Created August 28, 2014 08:32
Show Gist options
  • Save RinatMullayanov/0b92d2089f5579d19904 to your computer and use it in GitHub Desktop.
Save RinatMullayanov/0b92d2089f5579d19904 to your computer and use it in GitHub Desktop.
Sample modern prototype inheritance in Javacript
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product ' +
name + ' with a negative price');
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment