Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
how to use a variable in in an object in a javascript class

How do I make foo() work?

file1.js:

module.exports = class Example{

    constructor(something){
        
        this.something = something
    }

    functions ={

        foo(){

            return this.something
        }
    }
}

file2.js:

const Example = require('./file1.js')
const object = new Example("among")

console.log(object.foo())
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Remove 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 Relatório

0

First: you have to access those functions via .functions since that's where they live

Second, this will not be correct, so you can either

  • Make foo an arrow function

  • or you can .bind(this) to a function - like with bar in this code

  • you can't use .bind when using function property shorthand though - i.e. foo() { return this.something }.bind(this) - but you can bind it in the constructor

See the code for all three solutions - and why you need to bind the non arrow functions

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda