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

173
Visualizações
In Javascript, How to use a (global) function inside an object? The function would do complex stuff and would be used when creating objects

So, I was thinking of creating a function which does some stuff, and later use the same function inside different objects created later.

In the code below are two instances: Testing (01) and commenting out (02), and vice versa.

"use strict";

function fullName() {
    return this.firstName + " " + this.lastName;
}

const person = {
    firstName: "Anant",
    lastName: "Ghotale"
    completeName: fullName.call(person) // (01) does not work
};

//person.completeName = fullName.call(person); (02) this works


console.clear();
console.log(person.completeName);

(02) works, but (01) doesn't.

That is to say, creating a new property outside person while using call to put this = person works, but not inside it.

These are my questions:

  1. How do I use (call) a function inside an object?
  2. Is this a foolish endeavour, to call a function inside an object? Is there a better way to do the same task?
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You probably want to use a getter for this.

function fullName() {
  return this.firstName + " " + this.lastName;
}

const person = {
  firstName: "Anant",
  lastName: "Ghotale",
  get completeName() {
    return fullName.call(this)
  }
};

console.log(person.completeName)

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