How can I use variables from another function in javascript

后端 未结 2 935
孤街浪徒
孤街浪徒 2021-01-26 06:32

I cant have access to my variables from my function UserInfo all my variables are undefined. How can I have access to my variable and display them in my func

2条回答
  •  隐瞒了意图╮
    2021-01-26 06:38

    You are re-declaring your variables in UserInfo which causes them to hide the ones already declared in a higher scope. Just remove the let keyword on the variable assignments inside the function so that, instead of re-declaring smaller scoped variables, you use the already declared ones.

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

提交回复
热议问题