鍍金池/ 問答/HTML/ 在 javascript 中如何在創(chuàng)建類的時候返回 null?

在 javascript 中如何在創(chuàng)建類的時候返回 null?

比如有一個類,在聲明的時候參數(shù)不合法,這時候就不應該成功創(chuàng)建實例而是返回 null,請問如何實現(xiàn)?

另外,還有一個場景,如果我用 Array.some 來檢驗一個數(shù)組參數(shù),又如何讓其終止馬上返回 null 呢?

// demo: https://7kk7xolr7j.codesandbox.io/
class Foo {
  constructor(props) {
    for (let item in props) {
      try {
        console.log(item);
        if (item < 1) {
          throw new Error(item + " is invalid");
        }
      } catch (e) {
        console.error(e);
        return;
        // 終止初始化,返回 null
      }
    }
  }
}

let testArrA = [1, 1, 1, 0, 0];
let testArrB = [1, 1, 1, 1];
const b = new Foo(testArrB);
const a = new Foo(testArrA);
console.log(b, a); // expected `Foo?{} null` but get `Foo{} Foo?{}`



回答
編輯回答
別傷我

參數(shù)不正確應該拋出異常

2017年6月23日 16:08
編輯回答
女流氓

只要用了new就不可能返回null...

2017年11月24日 16:07