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

137
Visualizações
Referencing an object property inside itself

Suppose I have a javascript class like this:

class MyClass {
  constructor (a) {
    this.a = a;
  }

  foo() {
    // do something
  }

  bar() {
    const baz = this.foo();
    // do something with baz
  }
}

In the bar() function I can call the foo() function using this.

Is it possible to do this using an object instead of a class? For example:

const myObj = (a) => {
  return {
    foo: () => {
      // do something
    },
    bar: () => {
      const baz = foo(); // this doesn't work
      const baz = myObj.foo() // this doesn't work either
      // do something with baz
    }
  }
}

A solution I found is to define foo and bar outside of the object and then assign them to the object afterwards, but it doesn't feel right:

const myObj = (a) => {
  const foo = () => {
    // do something
  };
  const bar = () => {
    const baz = foo();
    // do something with baz
  };

  return { foo, bar };
}

Is there a way to reference an object's own property from inside of the object?

Edit: Thanks to the responders, an easy solution is to not use arrow functions, and then you can use this:

const myObj = (a) => {
  return {
    foo: function () {
      // do something
    },
    bar: function () {
      const baz = this.foo() // this works!
      // do something with baz
    }
  }
}
about 4 years ago · Juan Pablo Isaza
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