0

In Java, I can create variables from prompts, then use a non-default object constructor and pass those prompt variables in as parameters to create a new instance of that object. Is there an equivalent to this in javaScript?

example in Java:

    String first = JOptionPane.showInputDialog("What is your first name?");
    String last = JOptionPane.showInputDialog("What is your last name?");
    String gender = JOptionPane.showInputDialog("What gender are you? Male of Female?");
    int month = Integer.parseInt(JOptionPane.showInputDialog("Enter the two digits of your birth month"));
    int day = Integer.parseInt(JOptionPane.showInputDialog("Enter the two digits of your birth day"));
    int year = Integer.parseInt(JOptionPane.showInputDialog("Enter the four digits of your birth year"));

    //I have this non-default constructor created in another Class
    HealthProfile health1 = new HealthProfile(first, last, gender, month, day, year); 

I've tried this several different ways in JS but can quite get it. I'm a beginner in both languages so, bear with me.

hack job attempt in javaScript:

var firstName = prompt("enter your first name");
var lastName = prompt("enter your last name");
var gender = prompt("enter your gender");
var birthMonth = prompt("enter the two digits of your birth month");
var birthDay = prompt("enter the two digits of your birth day");
var birthYear = prompt("enter the four digits of your birth year");

  function person(firstName, lastName, gender, birthMonth, birthDay, birthYear){
    this.firstName = {};
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthMonth = birthMonth;
    this.birthDay = birthDay;
    this.birthYear = birthYear;
}

Like I said, I've had this a few different ways without success. This is just my most recent attempt.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
C Morgan
  • 3
  • 1
  • 6

2 Answers2

0

This works:

var firstName = prompt("enter your first name");
var lastName = prompt("enter your last name");
var gender = prompt("enter your gender");
var birthMonth = prompt("enter the two digits of your birth month");
var birthDay = prompt("enter the two digits of your birth day");
var birthYear = prompt("enter the four digits of your birth year");

function person(firstName, lastName, gender, birthMonth, birthDay, birthYear){
   return {
       firstName: firstName,
       lastName: lastName,
       birthMonth: birthMonth,
       birthDay: birthDay,
       birthYear: birthYear
   };
}

var test = person(firstName, lastName, gender, birthMonth, birthDay, birthYear);
Lance
  • 1
  • 1
0

The answer is Yes. A function can be created in javaScript that can serve just as a non-default constructor in Java. You can prompt the user for information, assign a variable to their response then pass that variable as a parameter in your function.

In my code above I simply neglected to instantiate a new Person Object.

Thanks for the help guys!

C Morgan
  • 3
  • 1
  • 6