Maku
Maku

Reputation: 87

how to solve TypeError: Cannot read property 'push' of undefined in simple node project?

im trying to create a simple address book,

//globol object for contacts database
// Business Logic for AddressBook ---------
function AddressBook(contacts) {
    this.contacts = [];
}

AddressBook.prototype.addContact = (contact) => {
    this.contacts.push(contact);
}

// Business Logic for Contacts ---------
function Contact(firstName, lastName, phoneNumber) {
    this.firstName = firstName,
        this.lastName = lastName,
        this.phoneNumber = phoneNumber
}

Contact.prototype.fullName = () => {
    return this.firstName + " " + this.lastName;
}

var addressBook = new AddressBook();
var contact = new Contact("Ada", "Lovelace", "503-555-0100");
var contact2 = new Contact("Grace", "Hopper", "503-555-0199");
addressBook.addContact(contact);
addressBook.addContact(contact2);

console.log(addressBook.contacts);

but it prints the error

.../addressBook.js:8 this.contacts.push(contact); ^

TypeError: Cannot read property 'push' of undefined at AddressBook.addContact (/home/maku/Documents/epicodus/addressBook.js:8:19) at Object. (/home/maku/Documents/epicodus/addressBook.js:25:13) at Module._compile (internal/modules/cjs/loader.js:701:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10) at Module.load (internal/modules/cjs/loader.js:600:32) at tryModuleLoad (internal/modules/cjs/loader.js:539:12) at Function.Module._load (internal/modules/cjs/loader.js:531:3) at Function.Module.runMain (internal/modules/cjs/loader.js:754:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:622

Upvotes: 0

Views: 1198

Answers (2)

Ferguson Iyara
Ferguson Iyara

Reputation: 11

The arrow function changes the scope of the 'this' keyword, in your addContact method, change the method to a function declaration and it'll remove the error

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 10081

Don't use the arrow function check this

If you use arrow functions, this won't be bound to the current instance. You need to create functions with the keyword function :

function AddressBook(contacts) {
    this.contacts = [];
}

AddressBook.prototype.addContact = function(contact) {
    this.contacts.push(contact);
}

// Business Logic for Contacts ---------
function Contact(firstName, lastName, phoneNumber) {
    this.firstName = firstName,
        this.lastName = lastName,
        this.phoneNumber = phoneNumber
}

Contact.prototype.fullName = function() {
    return this.firstName + " " + this.lastName;
}

var addressBook = new AddressBook();
var contact = new Contact("Ada", "Lovelace", "503-555-0100");
var contact2 = new Contact("Grace", "Hopper", "503-555-0199");
addressBook.addContact(contact);
addressBook.addContact(contact2);

console.log(addressBook.contacts);

Upvotes: 2

Related Questions