此范围在addeventlistener回调中丢失

时间:2018-10-08 10:04:51

标签: javascript ecmascript-6 arrow-functions

您可以在下面看到我的ES6代码进行API调用,然后用返回的数据填充容器(1个数据= 1个.searchResult子元素)。我想在每个调用类mousedown中的回调方法的事件监听器上添加一个p_selectResult事件监听器。

问题是,当我在回调箭头函数中console.log(this.p_selectResult)(在for循环内)时,我不确定。

class WeatherApp {

/*******......*********/

/**
 * Auto completion
 */
p_handleAutoCompletion() {

    let searchValue = document.querySelector('#searchInput').value;

    if (searchValue !== '') {
        let xhttp = new XMLHttpRequest();
        xhttp.addEventListener('readystatechange', () => {
            if (xhttp.readyState === 4 && xhttp.status === 200) {

                // some code...

                let results = document.querySelectorAll('.searchResult');
                for (let i = 0; i < results.length; i += 1) {
                    console.log(this.p_selectResult); //this.p_selectResult undefined
                    results[i].addEventListener('mousedown', this.p_selectResult); 
                }
            }
        });
        let requestAddr = '...';
        xhttp.open('GET', requestAddr, true);
        xhttp.send();
    }
    else {
        /*...*/
    }
}

p_selectResult() {
    console.log('yes');
}

   /***.......*****/
}

0 个答案:

没有答案