Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Created March 11, 2013 00:03
Show Gist options
  • Select an option

  • Save hughfdjackson/5131088 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/5131088 to your computer and use it in GitHub Desktop.
// 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)
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