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.
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.
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.
Predefined constructors all produce an object when invoked with new , although they return a primitive value when called as regular functions.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With