为了练习我对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,以便可以在全局范围内访问它们?
答案 0 :(得分:3)
如果我正确理解了您的问题,那么在处理与事件处理程序相关的数据/变量时,通常的模式是在那些事件处理程序的范围之外声明这些变量(即在“全局”范围内,如下所示) ,而不是从事件处理程序中返回该变量:
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>
希望这会有所帮助!
答案 1 :(得分:1)
因为要在函数内部创建对象,所以对象仅存在于函数范围内,无法在函数外部访问。您可以尝试制作全局变量并将其分配给函数:
var male1;
var female1;
/* Create person */
male.addEventListener('click', function() {
male1 = new Person('male');
});
female.addEventListener('click', function() {
female1 = new person('female');
});