Home > Software engineering >  In Javascript, How to use a (global) function inside an object? The function would do complex stuff
In Javascript, How to use a (global) function inside an object? The function would do complex stuff

Time:10-21

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?

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related