How to add a method to an array object that was made by a construction function

Viewed 63

trying to solve the following problem.

I have a construction function like:

function Person (name){
  this.firstName = name;
}

than I make some objects:

var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");

and finally attach them together:

var family = [myFather, myMother, myChild];

Now I would like to attach a method driver() to 'family', that will use the 'firstName' variable from the constructor function to choose, who is going to drive

2 Answers

Use another class Family and add a setDriver method to it:

function Person (name){
  this.firstName = name
}

function Family (members){
  this.members = members;
  this.driver = members[0];
  this.setDriver = function(name){
    this.driver = this.members.filter(member => member.firstName == name)[0]
  }
}

var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");

var family = new Family([myFather, myMother, myChild]);
console.log(family.driver)

family.setDriver("Sonny")
console.log(family.driver)

// At first you should remove comma from you Person function, and use semicolon(;)

// Just create function

function driver(firstName = this.firstName) {
    console.log(`Drive is ${firstName}`)
}

driver.call(this, family[0].firstName)

// Result Drive is John

// or you can directly call driver function as method of any family object like

driver.call(family[0])

// Above code will produce same result, please try this

Related