Home:ALL Converter>Returning a Javascript Object in a function

Returning a Javascript Object in a function

Ask Time:2018-12-05T03:24:41         Author:Alec Champaign

Json Formatter

To practice my knowledge of Javascript objects, I made a very simple program:

const male = document.querySelector('.male');
const female = document.querySelector('.female');

/* Person constructor */
function Person (gender) {
    this.gender = gender;


Person.prototype.bio = function() {
    alert('This person is ' + this.gender + '.');

/* Create person */
male.addEventListener('click', function() {
    let male1 = new Person('male');

    return male1;

female.addEventListener('click', function() {
    let female1 = new person('female');

    return female1;

However, I've run into a scope issue: I cannot call the male1 or female1 objects in global scope. Running


in the browser console returns the following error:

ReferenceError: male1 is not defined

How do I properly return the new objects, male1 and female1, so that I can access them in the global scope?

Author:Alec Champaign,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53620070/returning-a-javascript-object-in-a-function
Dacre Denny :

If I understand your question correctly, then the general pattern when working with data/variables in relation to an event handler is to declare those variables outside the scope of that event handler (ie in the \"global\" scope as shown below), rather than to return that variable from your event handler:\n\n\r\n\r\nconst male = document.querySelector('.male');\r\nconst female = document.querySelector('.female');\r\n\r\n// Declare male1,female1 in global scope\r\nlet male1;\r\nlet female1;\r\n\r\n/* Person constructor */\r\nfunction Person (gender) {\r\n this.gender = gender;\r\n \r\n}\r\n\r\nPerson.prototype.bio = function() {\r\n alert('This person is ' + this.gender + '.');\r\n};\r\n\r\n/* Create person */\r\nmale.addEventListener('click', function() {\r\n \r\n // update global variables like so\r\n male1 = new Person('male');\r\n \r\n // return male1;\r\n});\r\n\r\nfemale.addEventListener('click', function() {\r\n \r\n // update global variables like so\r\n female1 = new Person('female');\r\n\r\n //return female1;\r\n});\r\n\r\n// Added this to demonstrate how global variables are updated\r\n// after click events are fired\r\nsetInterval(function() {\r\n console.log('male1',male1);\r\n console.log('female1',female1);\r\n}, 1000);\r\n<button class=\"male\">Male</button>\r\n<button class=\"female\">Female</button>",