停止构造函数

时间:2014-03-04 19:09:34

标签: javascript design-patterns

我正在尝试将一种构造函数模式实现到项目的库中。但是,我想检查在返回对象之前传递的某些条件。如果不满足这些条件,那么我想停止构造函数并返回false

但是,我注意到无论我将其设置为返回值,都会返回一个对象!

即使我这样做了:

new function () { return false; }

结果仍是Object对象:

在Chrome中:

Chrome console

在Firefox中:

Firefox console

在Javascript中有没有办法让构造函数失败?

3 个答案:

答案 0 :(得分:6)

  

如果不满足这些条件,那么我想停止构造函数并返回false。

你做不到。除非它是非null对象,否则将忽略构造函数的返回值。任何原始值(或null)都会被new表达式忽略。

如果你真的想要返回一个标志值,你可以这样做,但它必须是一个对象。 (但这不是一个坏主意,更多信息如下。)例如:

// The constructor
function Foo(num) {
    if (num < 27) {
        return Foo.BAD_ARG; // This is a bad idea, see the right way below
    }
    this.num = num;
}
Foo.BAD_ARG = {}; // Our special "bad argument" object
  

在Javascript中有没有办法让构造函数失败?

是:抛出异常:

function Foo(num) {
    if (num < 27) {
        throw "`num` must be >= 27";
    }
    this.num = num;
}

答案 1 :(得分:1)

返回非对象的唯一方法是将构造函数包装在函数中,然后使用new为它调用(或不调用)。

为此,需要禁止外部函数new


您甚至可以使用相同的功能,只要您从未使用new调用它。

function Foo() {
   if (!(this instanceof Foo)) {
       if (some_condition)
           return false;
       else
           return new Foo()
   }
   // your constructor code here
}

var x = Foo();

如果您忘记并意外使用new,则存在危险。要解决此问题,您可以使用单独的功能。

function Foo() {
    // constructor code
}

function Bar() {
    if (this instanceof Bar)
        throw "Not a constructor"

    if (some_condition)
         return false;
    else
        return new Foo();
}

答案 2 :(得分:1)

从堆栈中抛出错误,例如

function thing(){
    throw new Error('nope');
}

try {
    var mine = new thing();
}
catch( e ){
    mine = null;
}

// mine is null

你也可以做一种工厂方法,比如:

createThing = function(){
   var obj = new thing();
   if( obj.feelsOK ){
       return obj;
   }
}

mine = createThing();
// mine is null