gpt4 book ai didi

javascript - 在函数中返回 Javascript 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:25 25 4
gpt4 key购买 nike

为了练习我对 Javascript 对象的了解,我编写了一个非常简单的程序:

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

但是,我遇到了范围问题:我无法在全局范围内调用 male1 或 female1 对象。运行

male1;

在浏览器控制台返回如下错误:

ReferenceError: male1 is not defined

如何正确返回新对象 male1 和 female1,以便我可以在全局范围内访问它们?

最佳答案

如果我正确理解你的问题,那么在处理与事件处理程序相关的数据/变量时的一般模式是在该事件处理程序的范围之外声明这些变量(即在“全局”范围内,如下所示) ,而不是从您的事件处理程序返回该变量:

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

// Declare male1,female1 in global scope
let male1;
let female1;

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

}

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

/* Create person */
male.addEventListener('click', function() {

// update global variables like so
male1 = new Person('male');

// return male1;
});

female.addEventListener('click', function() {

// update global variables like so
female1 = new Person('female');

//return female1;
});

// Added this to demonstrate how global variables are updated
// after click events are fired
setInterval(function() {
console.log('male1',male1);
console.log('female1',female1);
}, 1000);
<button class="male">Male</button>
<button class="female">Female</button>

希望这对您有所帮助!

关于javascript - 在函数中返回 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com