Created
May 29, 2011 12:06
-
-
Save glenjamin/997720 to your computer and use it in GitHub Desktop.
"Static" methods in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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