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

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