How to enable the use of static methods while preventing the use of instance functions without using the new operator? In the example below, the constructor will throw an exception if you try to invoke it without the new operator. Unfortunately, this also prevents access to genuine static functions in the prototype, that are perfectly ok to invoke without constructing an object first:
function TestIt() {
if(this.constructor == arguments.callee && !this._constructed )
this._constructed = true;
else
throw "this function must be called with the new operator";
}
TestIt.prototype.someStaticMethod=function() {
console.log('hello');
}
TestIt.prototype.someStaticMethod(); //ok
var t=new TestIt();
t.someStaticMethod(); //ok
TestIt.someStaticMethod(); //exception raised
Is there a way to get TestIt.someStaticMethod()
to work in this context anyway?
Why does TestIt.someStaticMethod()
actually call the constructor in the first place? It is a bit counterintuitive that it does so.