Created
January 4, 2018 20:34
-
-
Save SakoMe/d5c5b4d894d21765ab2450f4184df23a to your computer and use it in GitHub Desktop.
Classes vs Prototype vs Functional Approach
This file contains hidden or 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
/** | |
|-------------------------------------------------- | |
| CLASSES | |
|-------------------------------------------------- | |
*/ | |
class Point { | |
constructor(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
moveBy(dx, dy) { | |
this.x += dx; | |
this.y += dy; | |
} | |
} | |
const point = new Point(0, 0); | |
point.moveBy(5, 5); | |
point.moveBy(-2, 2); | |
console.log('===================================='); | |
console.log([point.x, point.y]); | |
console.log('===================================='); | |
/** | |
|-------------------------------------------------- | |
| PROTOTYPE | |
|-------------------------------------------------- | |
*/ | |
function PointProto(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
PointProto.prototype.moveByProto = function(dx, dy) { | |
this.x += dx; | |
this.y += dy; | |
}; | |
const pointProto = new PointProto(0, 0); | |
pointProto.moveByProto(5, 5); | |
pointProto.moveByProto(-2, 2); | |
console.log('===================================='); | |
console.log([pointProto.x, pointProto.y]); | |
console.log('===================================='); | |
/** | |
|-------------------------------------------------- | |
| PURE FUNCTIONS - FUNCTIONAL STYLE | |
|-------------------------------------------------- | |
*/ | |
const createPoint = (x, y) => Object.freeze([x, y]); | |
const movePointBy = ([x, y], dx, dy) => { | |
return Object.freeze([x + dx, y + dy]); | |
}; | |
let pointFunc = createPoint(0, 0); | |
pointFunc = movePointBy(pointFunc, 5, 5); | |
pointFunc = movePointBy(pointFunc, -2, 2); | |
console.log('===================================='); | |
console.log(pointFunc); | |
console.log('===================================='); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment