Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-pushing object constructor

Tags:

javascript

oop

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.

like image 511
gchiconi Avatar asked Nov 24 '13 00:11

gchiconi


People also ask

Can we use push method on object?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.

How do you push an object to an existing array?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.

Can a JavaScript constructor return a primitive value?

Predefined constructors all produce an object when invoked with new , although they return a primitive value when called as regular functions.

How do you push an array of objects into an array?

To achieve this, we'll use the push method. As you can see, we simply pass the obj object to the push() method and it will add it to the end of the array. To add multiple objects to an array, you can pass multiple objects as arguments to the push() method, which will add all of the items to the end of the array.


1 Answers

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)
}
like image 193
rdodev Avatar answered Sep 22 '22 13:09

rdodev