Created
October 16, 2014 17:03
-
-
Save keyvanakbary/d225ee7371b4c856e2be to your computer and use it in GitHub Desktop.
Prototype vs Object.create
This file contains 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
//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