0

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

2
  • 2
    you are missing "new" var guy = new Person(firstName, lastName, areaCode, phone); Commented Sep 21, 2014 at 15:57
  • 3
    Also, you aren't using the return value. Commented Sep 21, 2014 at 15:59

1 Answer 1

4

Your code had three problems:

  • When you instantiate a constructor, you must use new.
  • If you declare a variable (guy) inside a function, it won't be accessible from the outside. 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. 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);

Sign up to request clarification or add additional context in comments.

7 Comments

Missing var for the four variables in getInfo, don't want them using outer scope
problem 4, not using the return value of getInfo()
@Oriol getting there – now the first two are local... ;-)
@bmceldowney I think OP didn't use the return value because he thought that defining guy inside getInfo made it available outside too.
Seems possible, but considering the title of the question is about returning an object from a function, it might be worthwhile to point out that he's returning the object correctly but he's just not doing anything with it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.