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

时间:2020-09-09 04:46:23

标签: javascript

我正在尝试使用通过按钮单击事件创建的对象。该对象稍后在代码中可用。最后一个控制台语句打印未定义。如何在代码中返回该对象以供以后使用?谢谢。

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

1 个答案:

答案 0 :(得分:1)

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