Skip to content

Instantly share code, notes, and snippets.

@samoshkin
Created December 27, 2012 01:03
Show Gist options
  • Save samoshkin/4384536 to your computer and use it in GitHub Desktop.
Save samoshkin/4384536 to your computer and use it in GitHub Desktop.
Constructor function as class in JavaScript.
// type declaration
var A = makeType({
init: function(x, y){
this.x = x;
this.y = y;
},
hello: function(){
console.log(this.x, this.y)
}
});
// B is subclass of A
var B = makeType(A, {
init: function(x, y, z){
// call super
Object.getPrototypeOf(B.prototype).init.call(this, x, y);
this.z = z;
},
run: function(){
console.log("running", this.z)
}
});
function makeType(){
var base, declaration;
if(typeof arguments[0] == "function"){
base = arguments[0];
declaration = arguments[1];
} else {
declaration = arguments[0];
}
function Ctor(){
var self = this;
if(!(this instanceof Ctor)){
self = Object.create(Ctor.prototype);
}
self.init.apply(self, arguments);
return self;
}
var proto = Object.create((base && base.prototype) || Object.prototype);
Object.getOwnPropertyNames(declaration).forEach(function(propName){
proto[propName] = declaration[propName];
});
Ctor.prototype = proto;
return Ctor;
}
// usage
var assert = require("assert");
// create using new
var a1 = new A(1, 2);
assert.ok(a1 instanceof A);
assert.ok(A.prototype.isPrototypeOf(a1));
assert.notEqual(A.prototype.constructor, A);
a1.hello();
// new does not matter
var a2 = A(1, 2);
assert.ok(a2 instanceof A);
assert.ok(A.prototype.isPrototypeOf(a2));
assert.notEqual(A.prototype.constructor, A);
a2.hello();
// check B which is a subclass of A
var b1 = new B(1, 2, 3);
assert.ok(b1 instanceof B);
assert.ok(b1 instanceof A);
b1.hello();
b1.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment