gpt4 book ai didi

Javascript-从函数返回一个对象

转载 作者:行者123 更新时间:2023-11-28 15:34:52 24 4
gpt4 key购买 nike

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

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

关于Javascript-从函数返回一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com