Skip to content

Instantly share code, notes, and snippets.

@keyvanakbary
Created October 16, 2014 17:03
Show Gist options
  • Save keyvanakbary/d225ee7371b4c856e2be to your computer and use it in GitHub Desktop.
Save keyvanakbary/d225ee7371b4c856e2be to your computer and use it in GitHub Desktop.
Prototype vs Object.create
//CLASSIC PROTOTYPE
var Rectangle = function (width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
}
(new Rectangle(4, 5)).area()//20
var Square = function (side) {
this.width = side;
this.height = side;
}
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
(new Square(4)).area()//16
//OBJECT CREATE
var Rectangle = {
create: function (width, height) {
var obj = Object.create(this);
obj.width = width;
obj.height = height;
return obj;
},
area: function () {
return this.width * this.height;
}
};
Rectangle.create(4, 5).area();//20
var Square = Object.create(Rectangle);
Square.create = function (side) {
return Rectangle.create(side, side);
}
Square.create(4).area();//16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment