3

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

asked Mar 30, 2020 at 17:22

2 Answers 2

1

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)

answered Mar 30, 2020 at 17:26
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Mar 30, 2020 at 17:48

2 Comments

I don't think this code makes much sense, it is like writing an unrelated function that displays whatever variable is passed to it
// At first you should remove comma from you Person function, and use semicolon(;) Thanks for pointing out. Have corrected it!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.