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

172
Views
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 answers
Answer question

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