Skip to content

Instantly share code, notes, and snippets.

@glenjamin
Created May 29, 2011 12:06
Show Gist options
  • Save glenjamin/997720 to your computer and use it in GitHub Desktop.
Save glenjamin/997720 to your computer and use it in GitHub Desktop.
"Static" methods in javascript
// To be run under NodeJS
var util = require('util');
function Parent() {}
Parent.tableName = 'parentTable';
Parent.prototype.static_method = function() {
return this.constructor.tableName;
}
function Child() {}
Child.tableName = 'childTable';
util.inherits(Child, Parent);
// Internally this does:
// Child.super_ = Parent;
// Child.prototype = Object.create(Parent.prototype, {
// constructor: { value: Child, enumerable: false }
// });
var p = new Parent();
var c = new Child();
/*** Static Method called properly ***/
console.log(Parent.prototype.static_method()); // => parentTable
console.log(Child.prototype.static_method()); // => childTable
/*** Static Method called "wrongly" ***/
console.log(p.static_method()); // => parentTable
console.log(c.static_method()); // => childTable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment