Last active
March 2, 2016 07:24
-
-
Save eshacker/be153d852b9b995f42dd to your computer and use it in GitHub Desktop.
Wrong versus right way to do OO in JS
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
/* Reading https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch1.html | |
* I have a differing opinion. Please help in sorting it out. | |
*/ | |
// Original code : or I think wrong way to to Object Oriented code. | |
var Flock = function(n) { | |
this.seagulls = n; | |
}; | |
Flock.prototype.conjoin = function(other) { | |
this.seagulls += other.seagulls; | |
return this; | |
}; | |
Flock.prototype.breed = function(other) { | |
this.seagulls = this.seagulls * other.seagulls; | |
return this; | |
}; | |
var flock_a = new Flock(4); | |
var flock_b = new Flock(2); | |
var flock_c = new Flock(0); | |
var result = flock_a.conjoin(flock_c) | |
.breed(flock_b).conjoin(flock_a.breed(flock_b)).seagulls; | |
console.log(result); // 32 | |
// --------------------------------------------------------------------// | |
// My code or the way I think to right way to do OOC | |
var Flock = function(n) { | |
this.seagulls = n; | |
}; | |
Flock.prototype.conjoin = function(other) { | |
return new Flock(this.seagulls + other.seagulls); | |
}; | |
Flock.prototype.breed = function(other) { | |
return new Flock(this.seagulls * other.seagulls); | |
}; | |
var flock_a = new Flock(4); | |
var flock_b = new Flock(2); | |
var flock_c = new Flock(0); | |
var result = flock_a.conjoin(flock_c) | |
.breed(flock_b).conjoin(flock_a.breed(flock_b)).seagulls; | |
console.log(result); //16 |
Flock.prototype.conjoin = function(other) {
return new Flock(this.seagulls + other.seagulls);
};
Flock.prototype.breed = function(other) {
return new Flock(this.seagulls * other.seagulls);
};
For the incessant optimizer in me.
conjoin and breed are not pure functions. They depend on mutable variable this.seagulls
flock_a.confoin(flock_b) don't always return same result. If value of seagulls in flock_a is changed, then return value will differ.
Check chapter 3 in the book. Author clearly explained this scenario. He recommends you to use Object.freeze.
Yes the problem with Object.freeze is that a) things can get to the Object before it is frozen and b) attempts to modify the frozen object silently succeed, even without changing anything and without generating any error condition/exception or similar.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd have better OO example that really throws light on problems OO solve, and then reason why we need functional way of thinking. Think, if villain in Terminator 2 was weaker, would we have loved the heroic acts that much?