Created
March 11, 2013 00:03
-
-
Save hughfdjackson/5131088 to your computer and use it in GitHub Desktop.
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
| // as an approximation of the classical model, Num will return an object with methods on it | |
| // these methods cannot be added to at run-time for all numbers, since there's no prototype | |
| // chain going on here | |
| var Num = function(val){ | |
| return { | |
| val: val, | |
| mul: function(val) { return Num(this.val * val) }, | |
| div: function(val) { return Num(this.val / val) }, | |
| add: function(val) { return Num(this.val + val) }, | |
| sub: function(val) { return Num(this.val + val) } | |
| } | |
| } | |
| var one = Num(1) | |
| var two = one.add(1) |
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
| var extend = function(t, f){ for ( var p in f ) t[p] = f[p]; return t; } | |
| var derive = function(parent, o){ return extend(Object.create(parent), o) }; | |
| // here, we have a number prototype, which can be extended at runtime. all numbers | |
| // will inherit from this | |
| var Num = { | |
| mul: function(val) { return derive(Num, { val: this.val * val }) }, | |
| div: function(val) { return derive(Num, { val: this.val / val }) }, | |
| add: function(val) { return derive(Num, { val: this.val + val }) }, | |
| sub: function(val) { return derive(Num, { val: this.val - val }) } | |
| } | |
| var one = derive(Num, { val: 1 }) | |
| var two = one.add(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment