简体   繁体   中英

strange behavior of this keywork in JS

I have some code, which is really simple, but if I use this keyword, it won't work. I already searched internet, but this keyword is still a mystery.

Anyone can explain to me why?

let backdrop = document.querySelector('.backdrop');
let modal = document.querySelector('.modal')
let selectPlanButtons = document.querySelectorAll('.plan button');
let modalBoBtn = document.querySelector('.modal__action--negative');
let toggleBtn = document.querySelector('.toggle-button');
let mobileNav = document.querySelector('.mobile-nav');

for(let i=0; i<selectPlanButtons.length; i++){
    selectPlanButtons[i].addEventListener('click', showModal);    
}

backdrop.addEventListener('click', closeBackdrop);
modalBoBtn.addEventListener('click', closeModal);
toggleBtn.addEventListener('click', closeShowToggleBtn);

function closeBackdrop(){
    mobileNav.style.display = 'none';
    closeModal(); // if change to this.closeModal(); => won't work
}

function closeShowToggleBtn(){
    mobileNav.style.display = 'block';
    backdrop.style.display = 'block';
}

function showModal(){
    modal.style.display = 'block';
    backdrop.style.display = 'block';
};

function closeModal(){
    modal.style.display = 'none';
    backdrop.style.display = 'none';
};

The catch here is that in JavaScript for a regular function this refers to its execution context. When you register backdrop.addEventListener('click', closeBackdrop); closeBackdrop() will be called in the context of an HTML element, I'm guessing HTMLButtonElement in this case. Because of that, inside closeBackdrop() this refers to the HTML element that handles the click event. showModal() is defined in the global context and so it is undefined on this HTML element where closeBackdrop() is being called. Here you can find a more complete explanation on how this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM