Skip to content

Instantly share code, notes, and snippets.

@soharu
Last active January 2, 2016 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soharu/8284174 to your computer and use it in GitHub Desktop.
Save soharu/8284174 to your computer and use it in GitHub Desktop.
Factory function example
function inherit(p) {
if (p == null)
throw TypeError();
if (Object.create)
return Object.create(p);
var t = typeof p;
if (t !== "object" && t !== "function")
throw TypeError();
function f() {};
f.prototype = p;
return new f();
}
// factory function
function range(from, to) {
var r = inherit(range.methods);
r.from = from;
r.to = to;
return r;
}
// prototype object
range.methods = {
includes: function (x) {
return this.from <= x && x <= this.to;
},
foreach: function (f) {
for (var x = Math.ceil(this.from); x <= this.to; x++)
f(x);
},
toString: function () {
return "(" + this.from + "..." + this.to + ")";
}
}
var r = range(1, 3);
r.includes(2);
r.foreach(console.log);
console.log(r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment