Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Checking instanceof with a class

I have the following code:

function Complex(real, imaginary) {
    let c = Object.create(Complex.methods);
    [c.real, c.imaginary] = [real, imaginary];
    return c;
}

Complex.methods = {
    toString() {return `${this.real}+${this.imaginary}i`},
    add(other) {
        if (!(other instanceof Complex)) throw new Error("Only supports complex-only addition");
        return Complex(this.real+other.real, this.imaginary+other.imaginary);
    }
}
let c1 = Complex(2,0);
let c2 = Complex(3,4);
console.log(c1.add(c2) + "");
// "Uncaught Error: Only supports complex-only addition",

This is occurring because c1 instanceof Complex is returning false. Why does it return false?

Comparing it with using the class keyword:

class CX {
    toString() {return "xxx"}
}
let c1 = new CX();
console.log(c1 + "", c1 instanceof CX);
// xxx true

But still curious why the first one doesn't recognize the instanceof operator.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The OP either chooses the classic (good ol' days) constructor function approach ...

function Complex(real, imaginary) {
  Object.assign(this, { real, imaginary });
}
Complex.prototype.toString = function toString () {
  return `${this.real} + ${this.imaginary}i`
};
Complex.prototype.add = function add (other) {
  if (!(other instanceof Complex)) {
    throw new Error("Only supports complex-only addition");
  }
  return new Complex(
    this.real + other.real,
    this.imaginary + other.imaginary
  );
};
let c1 = new Complex(2,0);
let c2 = new Complex(3,4);

console.log(c1.add(c2) + "");
.as-console-wrapper { min-height: 100%!important; top: 0; }

... or a class based approach ...

class Complex {
  constructor(real, imaginary) {
    Object.assign(this, { real, imaginary });
  }
  toString () {
    return `${this.real} + ${this.imaginary}i`
  }
  add (other) {
    if (!(other instanceof Complex)) {
      throw new Error("Only supports complex-only addition");
    }
    return new Complex(
      this.real + other.real,
      this.imaginary + other.imaginary
    );
  }
}
let c1 = new Complex(2,0);
let c2 = new Complex(3,4);

console.log(c1.add(c2) + "");
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!