OOP Design & Patterns — Series 2

Preview — 3 of 10 questions

What is logged?

javascript
class Database {
  static #instance;

  constructor() {
    if (Database.#instance) {
      return Database.#instance;
    }
    Database.#instance = this;
    this.connectionId = Math.random();
  }
}

const db1 = new Database();
const db2 = new Database();

console.log(db1 === db2);
console.log(db1.connectionId === db2.connectionId);
Afalse, false
Btrue, false
Ctrue, true
Dfalse, true

What is logged?

javascript
class Even {
  static [Symbol.hasInstance](instance) {
    return Number.isInteger(instance) && instance % 2 === 0;
  }
}

console.log(4 instanceof Even);
console.log(7 instanceof Even);
console.log(new Number(4) instanceof Even);
Atrue, true, true
Btrue, false, true
Cfalse, false, false
Dtrue, false, false

What is logged?

javascript
class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new TypeError('Cannot instantiate abstract class Shape directly');
    }
  }
}

class Circle extends Shape {}

const c = new Circle();
console.log(c instanceof Shape);

try {
  new Shape();
} catch (e) {
  console.log(e.message);
}
Afalse, "Cannot instantiate abstract class Shape directly"
Btrue, "Cannot instantiate abstract class Shape directly"
Ctrue, nothing logged (no error is thrown)
DBoth instantiations throw an uncaught TypeError

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.