简体   繁体   English

Javascript-从函数返回对象

[英]Javascript- return an object from a function

I am trying to get a function that prompts a user for info and then passes that info to an object. 我正在尝试获取一个提示用户输入信息,然后将该信息传递给对象的函数。 So far it does not seem to be doing that. 到目前为止,似乎还没有这样做。

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

Your code had three problems: 您的代码有三个问题:

  • When you instantiate a constructor, you must use new . 实例化构造函数时,必须使用new
  • If you declare a variable ( guy ) inside a function, it won't be accessible from the outside. 如果在函数内部声明变量( guy ),则无法从外部访问该变量。 You can 您可以
    • Declare it outside, and set its value inside the function. 在外部声明它,并在函数内部设置它的值。
    • Return it to the outside. 将其返回到外面。 In this case you must use the return value. 在这种情况下,您必须使用返回值。
  • You didn't define variables inside getInfo . 您没有在getInfo定义变量。 Then, it will only work in non strict mode, and they will become globals, which may be bad. 然后,它将仅在非严格模式下工作,并且它们将成为全局变量,这可能是不好的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM