我有一个带有脚本的菜单,该脚本应该在打开页面时关闭,但是菜单脚本出现错误并且我的功能不起作用。
在控制台上给出这个错误:Uncaught ReferenceError:在初始化之前无法访问'_this'
我无法理解错误以及如何解决它。
错误:
我的编码 HTML:
为什么会报错?
function removeClassBody() {
var body = document.querySelector('body');
body.classList.remove('no-js'); //REMOVENDO a classe "no-js" do body
body.classList.add('js'); // ADICIONANDO a classe "js" no body
}
removeClassBody();
function menuConfig() {
var menu = new Menu({
container: '.header__nav',
toggleBtn: '.header__btnMenu',
widthEnable: 1024
});
}
menuConfig();
function Menu(config) {
this.nav = (typeof config.container === 'string') ?
document.querySelector(config.container) : config.container
this.btn = (typeof config.toggleBtn === 'string') ?
document.querySelector(config.toggleBtn) : config.toggleBtn
this.maxWidth = config.widthEnable || false;
this.btn.removeAttribute('style');
fechaMenu();
let _aberto = false;
let _this = this;
this.btn.addEventListener('click', abertoOuFechado);
function abertoOuFechado() {
if (!_aberto) {
abreMenu();
} else {
fechaMenu();
}
}
function abreMenu() {
let _top = _this.nav.getBoundingClientRect().top + 'px'
let _style = {
maxHeight: 'calc(100vh -' + _top + ' )',
overflow: 'hidden'
}
aplicandoStyleNaNav(_style);
_aberto = true;
}
function aplicandoStyleNaNav(_style) {
Object.keys(_style).forEach(stl => {
_this.nav.style[stl] = _style[stl]
})
}
function fechaMenu() {
let _style = {
maxHeight: '0px',
overflow: 'hidden'
}
aplicandoStyleNaNav(_style);
_aberto = false;
}
}
<!doctype html>
<html lang="pt-br">
<head>
<title> Infusion </title>
</head>
<body class="no-js">
<header class="header">
<a href="index.html" class="logo-text">Infusion</a>
<button style="display: none;" class="header__btnMenu">
<i class="fas fa-bars fa-2x"></i><span class="sr-only">Menu</span></button>
<nav class="header__nav">
<ul>
<li><a href="#">design folio</a></li>
<li><a href="#">services</a></li>
</ul>
</nav>
</header>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/menu.js"></script>
</body>
</html>