Javascript-从函数返回一个对象

时间:2014-09-21 15:56:20

标签: javascript

我正在尝试获取一个提示用户输入信息的函数,然后将该信息传递给对象。到目前为止,似乎并没有这样做。



// my object constructor
var Person = function (firstName, lastName, areaCode, phone) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.areaCode = areaCode;
  this.phone = phone;
}

// my function to get user info
function getInfo() {
  firstName = prompt("What is your first name: ");
  lastName = prompt("What is your last name: ");
  areaCode = prompt("What is your area code: ");
  phone = prompt("What is your phone number: ");
  var guy = Person(firstName, lastName, areaCode, phone);
  return guy;
}

// calling the function
getInfo();

// test to see if it actually worked
document.writeln(guy.firstName);




1 个答案:

答案 0 :(得分:4)

您的代码有三个问题:

  • 实例化构造函数时,必须使用new
  • 如果在函数内声明变量(guy),则无法从外部访问它。您可以
    • 将其声明为外部,并在函数内设置其值。
    • 将它归还给外面。在这种情况下,您必须使用返回值。
  • 您未在getInfo内定义变量。然后,它只能在非严格模式下工作,它们将成为全局变量,这可能是坏事。

// my object constructor
var Person = function (firstName, lastName, areaCode, phone) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.areaCode = areaCode;
  this.phone = phone;
}

// my function to get user info
function getInfo() {
  var firstName = prompt("What is your first name: "),
      lastName = prompt("What is your last name: "),
      areaCode = prompt("What is your area code: "),
      phone = prompt("What is your phone number: ");
  return new Person(firstName, lastName, areaCode, phone);
}

// calling the function
var guy = getInfo();

// test to see if it actually worked
document.writeln(guy.firstName);