Skip to content

Instantly share code, notes, and snippets.

@yurydelendik
Created November 27, 2012 14:05
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 yurydelendik/4154378 to your computer and use it in GitHub Desktop.
Save yurydelendik/4154378 to your computer and use it in GitHub Desktop.
class sugar
<!DOCTYPE html>
<html>
<body>
<script>
function const_(val) {
return { value: val, writable: false, enumerable: true, configurable: true };
}
function prop_(get, set) {
return { get: get, set: set, enumerable: true, configurable: true };
}
function extends_(baseClass) {
if (!(this instanceof extends_))
return new extends_(baseClass);
this.baseClass = baseClass;
}
function class_(cstr, ext, body) {
var c, i = 0;
if (arguments[i] instanceof Function)
c = arguments[i++];
var base = arguments[i] instanceof extends_ ? arguments[i++] : extends_(Object);
var props = {};
c = c || function() { base.baseClass.call(this); };
for (var j in arguments[i]) {
var prop = arguments[i][j];
props[j] = prop instanceof Function ?
{ value: prop, writable: false, enumerable: false, configurable: true } :
prop instanceof Object ? prop :
{ value: prop, writable: true, enumerable: true, configurable: true };
}
c.prototype = Object.create(base.baseClass.prototype, props);
return c;
}
var A = class_(function (a) { this.a = a; }, {
test: function () { return this.a; }
});
var a = new A(1);
var B = class_(function (a) { A.call(this, a); },
extends_(A), {
test: function () { return "super" + A.prototype.test.call(this); }
});
var b = new B(2);
function C() { A.call(this, 'C'); }
class_(C, extends_(A), {
c: const_("const"),
p: prop_(function () { return 1; })
});
var c = new C();
document.write(a instanceof A);
document.write(a instanceof B);
document.write(a.test());
document.write(b instanceof A);
document.write(b instanceof B);
document.write(b.test());
document.write(c instanceof A);
document.write(c instanceof B);
document.write(c instanceof C);
document.write(c.test());
document.write(c.c);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment