gchiconi gchiconi - 4 months ago 12
Javascript Question

Self-pushing object constructor

So JavaScript is a functional language, classes are defined from functions and the function scope corresponds to the class constructor. I get it all now, after a rather long time studying how to OOP in JavaScript.

What I want to do is not necessarily possible, so I first want to know if this is a good idea or not. So let's say I have an array and a class like the following:



var Entry = function(name, numbers, address) {
this.name = name;
if(typeof numbers == "string") {
this.numbers = [];
this.numbers.push(numbers);
}
else this.numbers = numbers;
this.address = address;
};

var AddressBook = [];


And I add contacts with the following function:

function addContact(name, numbers, address) {
AddressBook.push(new Entry(name, numbers, address));
}


Can't I make it so
new Entry()
would put itself into
AddressBook
? If I can't do this on create, it would be interesting to do it with a method in the
Entry
prototype as well. I couldn't figure out a way to do anything similar.

Answer

You could try passing the AddressBook array reference to the function like such:

var Entry = function(name, numbers, address, addressBook) {
  this.name = name;
  if(!(numbers instanceof Array)) {
    this.numbers = [numbers];
  }
  else this.numbers = numbers;
  this.address = address;
  addressBook.push(this);
};

var AddressBook = [];

function addContact(name, numbers, address) {
  new Entry(name, numbers, address, AddressBook)
}