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
cómo usar una variable en un objeto en una clase de javascript

¿Cómo hago que foo() funcione?

archivo1.js:

 module.exports = class Example{ constructor(something){ this.something = something } functions ={ foo(){ return this.something } } }

archivo2.js:

 const Example = require('./file1.js') const object = new Example("among") console.log(object.foo())
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Quitar functions :

 class Example{ constructor(something){ this.something = something; } foo(){ return this.something } } const object = new Example("among") console.log(object.foo())

about 4 years ago · Juan Pablo Isaza Report

0

Primero: debe acceder a esas funciones a través de .functions ya que es donde viven

En segundo lugar, this no será correcto, por lo que puede

  • Hacer foo una función de flecha

  • o puede .bind(this) a una función, como con la bar en este código

  • Sin embargo, no puede usar .bind cuando usa la propiedad de función abreviada, es decir, foo() { return this.something }.bind(this) , pero puede vincularlo en el constructor

Vea el código para las tres soluciones, y por qué necesita vincular las funciones que no son de flecha

 class Example{ constructor(something){ this.something = something; // bat needs to be bound here this.functions.bat = this.functions.bat.bind(this); } functions ={ // "this" will be correct here foo: () => this.something, // bar needs to be bound to "this" bar: function() { return this.something }.bind(this), // you can't bind a shorthand property function though bat() { return this.something }, // this is what happens with no bind baz() { return this.something }, } } const object = new Example("among") console.log('foo', object.functions.foo()) console.log('bar', object.functions.bar()) console.log('bat', object.functions.bat()) console.log('baz', object.functions.baz())

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!