2014-09-21 190 views
0

我想獲得一個函數,提示用戶輸入信息,然後將該信息傳遞給對象。到目前爲止,它似乎沒有這樣做。 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);

+2

你缺少 「新的」 變種人=新的Person(名字,姓氏,AREACODE,電話); – 2014-09-21 15:57:23

+3

另外,您沒有使用返回值。 – SLaks 2014-09-21 15:59:43

回答

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

+2

'getInfo'中的四個變量缺少'var',不希望它們使用外部作用域 – Shai 2014-09-21 16:03:52

+0

問題4,不使用'getInfo()' – bmceldowney 2014-09-21 16:06:46

+0

的返回值@Oriol到達那裏 - 現在前兩個是本地的。 .. ;-) – Shai 2014-09-21 16:08:18