我正在学习如何使用javascript类。我在理解如何使事件侦听器调用类中的方法时遇到了一些困难。具体来说,每当我单击click时调用this.infoBoxActive时,该方法中的所有变量都将返回undefined。
我最终想要做的是拥有一个onclick切换方法,onclick在true和false之间切换,然后根据其状态调用infoBoxActive或infoBoxDective。我整天都在尝试代码,尝试各种事情,但似乎引发了我的变量未定义的同一问题。如果我直接调用该方法,那么一切都会很好。
我一直在使用诺言从本地JSON文件中收集数据,但是我不确定如何以解析方式返回Object,所以现在我要从诺言中调用所有新类。我不知道这是否会成为问题的一部分。
我尝试阅读一些相似的帖子,但是我听不懂解决方案,或者与我的确切问题无关,因此,如果这是重复的,我深表歉意。
class EpisodeInfoBox extends Episode {
constructor({ title, date, description, tracklist } = {}) {
super({ title, date, description, tracklist })
this.titleContainer = document.querySelector('.episode-title');
this.dateContainer = document.querySelector('.episode-date');
this.descriptionContainer = document.querySelector('.episode-description');
this.tracklistContainer = document.querySelector('.episode-tracklist');
this.infoBoxButton = document.getElementById('infoBoxButton');
this.infoBoxButton.addEventListener('click', this.infoBoxActive);
}
infoBoxActive(){
this.titleContainer.innerHTML = this.title;
this.dateContainer.innerHTMLs = this.date;
this.descriptionContainer.innerHTML = this.description;
// Creates list-items for track list
let tracklistHTML = '';
for (let i = 0; i < this.tracklist.length; i++) {
tracklistHTML += `<li>${this.tracklist[i].song} - ${this.tracklist[i].artist}</li>`;
}
this.tracklistContainer.innerHTML = tracklistHTML;
}
}
我的诺言
export default function service(url) {
return new Promise(function(res, rej) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handleResponse;
xhr.onerror = function(error) {
rej(error)
}
xhr.send();
function handleResponse() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var resObject = JSON.parse(xhr.responseText);
res(resObject)
} else {
rej(this.statusText)
}
}
};
});
}
我的决心
function callService(){
service('/data/episodes.json')
.then(retrieveEpisode)
.then(makeEpisode)
.catch(function(e) {
console.log(e)
});
}
function retrieveEpisode(episodeArray) {
return episodeArray[0];
}
function makeEpisode(episode){
let newEpisode = new Episode(episode);
newEpisode.setEpisodeImage();
let newAudioPlayer = new AudioPlayer(episode);
let newEpisodeInfoBox = new EpisodeInfoBox(episode);
}
更改此:
this.infoBoxButton.addEventListener('click', this.infoBoxActive);
对此:
this.infoBoxButton.addEventListener('click', this.infoBoxActive.bind(this));
调用事件侦听器时,将不会this
设置对象的指针,因此infoBoxActive()
将使用不适当的值进行调用,this
因此您将看不到期望的属性。可以在调用方法之前使用.bind()
如上所示重新附加适当的this
值。
在Javascript中,当您将this.infoBoxActive
参数作为参数传递给函数时,将.infoBoxActive
传递对该方法的引用,但与根本没有任何联系this
。它只是对函数的引用。因此,侦听器然后调用该函数并设置其自己的值,this
该值将不是您的对象。使用,.bind()
您可以创建一个函数存根,该存根将this
在调用函数时为您设置的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句