如何在javascript中使用其他函数的变量

时间:2018-06-15 21:36:18

标签: javascript

我无法从我的函数UserInfo访问我的变量。我的所有变量都是未定义的。如何访问我的变量并在我的函数seeInfoUser

中显示它们
let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;  

let UserInfo = function(){
  let UserName = prompt("What is your name:");
  let UserAge = prompt("How old are you: ");
  let UserBirthPlace = prompt("Where were you born: ")
  let UserDream = prompt("What is your Greatest Dream: ");
}

let seeInfoUser = function (){              
  let UserInformation = ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`
  return UserInformation
}

let result = seeInfoUser(UserInfo());
console.log(result)

2 个答案:

答案 0 :(得分:3)

您正在UserInfo重新声明变量,这会导致它们隐藏已在更高范围内声明的变量。只需删除函数内变量赋值的let关键字,这样就可以使用已经声明的变量,而不是重新声明较小的范围变量。



// These variables will be available in the current scope and descendent scopes
let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;  
    
let UserInfo = function(){
  // ...So, don't re-declare the variables - just use them!
  UserName = prompt("What is your name:");
  UserAge = prompt("How old are you: ");
  UserBirthPlace = prompt("Where were you born: ")
  UserDream = prompt("What is your Greatest Dream: ");
}
    
let seeInfoUser = function (){
  // You really don't need to declare a variable if all you are going to do is return its value
  return ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`;
}
    
let result = seeInfoUser(UserInfo());
console.log(result)




答案 1 :(得分:1)

您的代码的问题是变量的范围。在javascript中,使用let声明的所有变量都具有块范围。并且您在UserInfo函数中重新声明它们,因此您应该只使用已经声明的变量。



let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;


let UserInfo = function() {
  UserName = prompt("What is your name:");
  UserAge = prompt("How old are you: ");
  UserBirthPlace = prompt("Where were you born: ")
  UserDream = prompt("What is your Greatest Dream: ");
}

let seeInfoUser = function() {

  let UserInformation = ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`

  return UserInformation
}



let result = seeInfoUser(UserInfo());
console.log(result)