Javascript-从函数返回一个对象
我想获得一个函数,提示用户输入信息,然后将该信息传递给对象。到目前为止,它似乎没有这样做。 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);
你的代码有三个问题:
- 当实例构造函数,你必须使用
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);
'getInfo'中的四个变量缺少'var',不希望它们使用外部作用域 – Shai 2014-09-21 16:03:52
问题4,不使用'getInfo()' – bmceldowney 2014-09-21 16:06:46
的返回值@Oriol到达那里 - 现在前两个是本地的。 .. ;-) – Shai 2014-09-21 16:08:18
你缺少 “新的” 变种人=新的Person(名字,姓氏,AREACODE,电话); – 2014-09-21 15:57:23
另外,您没有使用返回值。 – SLaks 2014-09-21 15:59:43