如何在不使用new运算符的情况下禁止使用实例函数的同时启用静态方法?在下面的示例中,如果您尝试在没有new运算符的情况下调用它,则构造函数将引发异常。不幸的是,这也阻止了对原型中真正的静态函数的访问,而这些静态函数完全可以在不首先构造对象的情况下调用:

    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


无论如何,有没有办法让TestIt.someStaticMethod()在这种情况下工作?
为什么TestIt.someStaticMethod()实际上首先调用构造函数?这样做有点违反直觉。

最佳答案

测试是否在不使用new的情况下调用构造函数的更简单方法是:

function TestIt() {
  if (!(this instanceof TestIt)) {
    throw "this function must be called with the new operator";
  }
}


至于静态方法,您也许应该在类(构造函数)上而不是在原型上进行定义。实例可访问原型上定义的属性,而类本身可访问静态方法。

TestIt.someStaticMethod = function() {
  console.log('hello');
}

var t=new TestIt();
t.someStaticMethod(); // no method here, exception

TestIt.someStaticMethod(); // works

10-05 20:35
查看更多