如何将提示作为对象/函数参数传递

时间:2014-03-23 14:31:21

标签: javascript object function-parameter

在Java中,我可以根据提示创建变量,然后使用非默认对象构造函数并将这些提示变量作为参数传递,以创建该对象的新实例。在javaScript中是否有相同的东西?

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); 

我在JS中已经尝试了几种不同的方法,但可以完全理解它。我是两种语言的初学者,请耐心等待。

在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;
}

就像我说的那样,我有几种不同的方法没有成功。这只是我最近的尝试。

2 个答案:

答案 0 :(得分:0)

这有效:

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);

答案 1 :(得分:0)

答案是肯定的。可以在javaScript中创建一个函数,该函数可以作为Java中的非默认构造函数。您可以提示用户输入信息,为其响应分配变量,然后将该变量作为函数中的参数传递。

在上面的代码中,我只是忽略了实例化一个新的Person对象。

感谢帮助人员!