lobsterhands
lobsterhands

Reputation: 88

JavaScript Immediately push to array inside 'new function()'

I'm new to JS (and programming), so forgive me if my terminology is incorrect. I have run searches based on the way I can think about this, which may be faulty, and I have not found what I'm looking for.

The following code works to build up my charList array. However, is there a way to include a charList.push(x) inside of the constructor in order to immediately and automatically push a new character to the array when I run the new character() constructor-function?

var charList = [];

function character (name, jobTitle) {
  this.name = name;
  this.jobTitle = jobTitle;
}

charList.push(new character("Sarah", "Nurse"));
charList.push(new character("Bob", "Doctor"));
console.log(charList);

Upvotes: 0

Views: 100

Answers (1)

Pointy
Pointy

Reputation: 413720

You can add:

charList.push(this);

in the constructor.

Upvotes: 2

Related Questions