Last active
August 29, 2015 13:56
-
-
Save jagoda/9176185 to your computer and use it in GitHub Desktop.
Factories and Constructors
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
function makeInstance (constructor, context) { | |
return context === global || context === undefined ? | |
Object.create(constructor.prototype) : | |
context; | |
} | |
function Rectangle (length, width) { | |
var rectangle = makeInstance(Rectangle, this); | |
rectangle.area = function () { | |
return length * width; | |
}; | |
return rectangle; | |
} | |
function Square (side) { | |
var square = makeInstance(Square, this); | |
Rectangle.call(square, side, side); | |
return square; | |
} | |
Square.prototype = Object.create(Rectangle.prototype); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment