-1

In this code sample:

level.js:

class Level {
  setLevel(level) {
    // if (typeof level === "number") {
    if (level.constructor === Number) {
      this._level = level;
    }
  }

  getLevel() {
    return this._level;
  }
}

module.exports = Level;

index.js:

const Level = require("./level");

let l = new Level();
l.setLevel(3);
console.log(l.getLevel());

I have 2 options of getting the type of input variable level: typeof or [var].constructor. Since JS is prototipical language, it seems more straightforward for me to use the one with constructor. Since every variable has one a it determines its real type. So why does everyone uses typeof and then compares its string result? (and hence are limit to only primitive types, whereas the constructor could be use witch custom/class variables)

milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • "So why does everyone uses typeof" who is everyone? For checking class `instanceof` is usually used. – Konrad May 15 '22 at 08:40

1 Answers1

0
  1. .constructor is mutable
    See: https://stackoverflow.com/a/39802529/19119805

  2. instanceof also checks for "inherited" constructors
    See: Difference between instanceof and constructor property

倪任爾
  • 232
  • 1
  • 4