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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.