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

179
Vistas
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 Respuestas
Responde la pregunta

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