Skip to content

Instantly share code, notes, and snippets.

@SakoMe
Created January 4, 2018 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SakoMe/d5c5b4d894d21765ab2450f4184df23a to your computer and use it in GitHub Desktop.
Save SakoMe/d5c5b4d894d21765ab2450f4184df23a to your computer and use it in GitHub Desktop.
Classes vs Prototype vs Functional Approach
/**
|--------------------------------------------------
| 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