Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
Verificando instancia de con una clase

Tengo el siguiente código:

 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",

Esto ocurre porque c1 instanceof Complex devuelve false . ¿Por qué devuelve falso?

Comparándolo con el uso de la palabra clave class :

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

Pero sigue siendo curioso por qué el primero no reconoce el operador instanceof .

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

El OP elige el enfoque de función de constructor clásico (buenos días) ...

 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; }

... o un enfoque basado en clases ...

 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda