We Made A Friend! (Constructor Solution)


#1

https://www.codecademy.com/courses/building-an-address-book/0/6?curriculum_id=506324b3a7dffd00020bf661


Couldn't find constructor solutions, so I posted this once I got a solution that passed... Used (this) inside of the new Object(); constructor to reference property values. Is that correct or did I get lucky?

Again, this solutions passes (green);


var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
	var contactsLength = contacts.length;
	for (var i = 0; i < contactsLength; i++) {
		printPerson(contacts[i]);
	}
}

/*Create a search function
then call it passing "Jones"*/
var search = function (lastName) {
    var contactsLength = contacts.length;
    for(var i = 0; i < contactsLength; i++) {
        if(contacts[i].lastName === lastName) {
            printPerson(contacts[i]);
        };
    };
};

search("Jones");

var add = function (firstName, lastName, email, phoneNumber) {
    
    contacts[contacts.length] = new Object(this);
    
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.phoneNumber = phoneNumber;
    
    };
    

    
add("Alex", "Prodoehl", "email@example.com", "(920) 392-0020");
list();


#2

Add this line to the bottom of your code and run it.

console.log(contacts[2]);

Not quite what we expect, eh?

The syntax is okay, since Object() can take an object, and this is an object, but with a whole lot of baggage. We do not wish to have all that data in our direct properties.

To use a custom constructor, write it as a separate function, and call it with your add() function.

function Contact(f, l, e, p) {
    this.firstName = f;
    this.lastName = l;
    this.email = e;
    this.phoneNumber = p;
}

and then,

var add = function (firstName, lastName, email, phoneNumber) {
    contacts.push(new Contact(firstName, lastName, email, phoneNumber));
};

Now run it with that last line and check the results.


#3

Ahhh. Gotcha!! Thank you for the helpful perspective / solution!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.