<a id="mylink" href="#">Click</a>
<script type="text/javascript">
class someClass {
constructor(params) {
this.mylink = params.link
}
hide() {
console.log('Hiding...');
}
show() {
console.log('Showing...');
}
handlerClick() {
console.log('Link clicked');
hide();
show();
}
start() {
this.mylink.addEventListener('click', this.handlerClick);
}
}
new someClass({
mylink: '#mylink'
}).start();
</script>
<a id="mylink" href="#">Click</a>
<script type="text/javascript">
class someClass {
constructor(params) {
this.mylink = document.querySelector(params.mylink);
}
hide() {
console.log('Hiding...');
}
show() {
console.log('Showing...');
}
// handler
handlerClick() {
console.log('Link clicked');
this.hide();
this.show();
}
start() {
this.mylink.addEventListener('click', this.handlerClick);
}
checkParams() {
console.log(`mylink: ${this.mylink}`);
}
}
new someClass({
mylink: '#mylink'
}).start();
</script>Uncaught TypeError: this.hide is not a function
...
handlerClick() {
console.log('Link clicked', this);
self.hide();
self.show();
}
start() {
window.self = this;
this.mylink.addEventListener('click', this.handlerClick);
}
...
handlerClick() {
console.log('Link clicked', this);
this.hide();
this.show();
console.log(this.counter++);
}
start() {
this.counter = 1;
this.mylink.addEventListener('click', this.handlerClick.bind(this, this.counter));
}