Javascript 正在为回调函数中创建的对象获取未定义

Javascript 正在为回调函数中创建的对象获取未定义,javascript,Javascript,我正在尝试使用从按钮单击事件创建的对象。该对象稍后在代码中可用。最后一条console语句打印未定义的内容。如何返回该对象以供以后在代码中使用?多谢各位 const btn = document.getElementById('btn'); // Use IIFE to get human data from form var getUserData = ( function () { function getInput() { let f

我正在尝试使用从按钮单击事件创建的对象。该对象稍后在代码中可用。最后一条console语句打印未定义的内容。如何返回该对象以供以后在代码中使用?多谢各位

const btn = document.getElementById('btn');
// Use IIFE to get human data from form
var getUserData = (
    function () {     
        function getInput() { 
          let formContainer = document.getElementsByClassName('form-container')[0];
          // Remove form from screen
          formContainer.classList.add('hide');
          //formContainer.style.display = 'none';
          let main = document.getElementById('grid');
          main.classList.remove('hide');
          main.classList.add('show');
          //main.style.display = 'flex';
          let name = document.getElementById('name').value;
                let feet = document.getElementById('feet').value;
          let inches = document.getElementById('inches').value;
          let height = (feet * 12) + inches;
          let weight = document.getElementById('weight').value;
          let diet = document.getElementById('diet').value;
            return { name: name, height: height, weight: weight, diet: diet};
        }
        return(getInput); 
})();

let human;

document.getElementById("btn").addEventListener("click", function (event) {  
    event.preventDefault();
    var user = getUserData();
    human = new Human(user.name, user.height, user.weight, user.diet);
    getHumanInfo(); // console logs the human
    return human; // returns udefined when I try to console log later in code
});

function getHumanInfo(){
  console.log(human);
}

// this returns udefined
console.log('Human: ' + human);

您正在添加事件侦听器,因此在对id为
btn
的元素执行单击之前不会调用回调。您正在立即记录变量
human
:由于尚未设置,因此不会对其进行定义。

由于事件侦听器代码仅在事件发生时执行,因此,对于最后一个console.log,不存在名为“human”的变量,谢谢Antoine。我移动了要在回调中执行的其余代码,以便可以使用该对象。