JavaScript本格入門[改訂新版]という本を読みながらJSの勉強をしているのですが、
以下のコードにおいて詰まってしまったので質問致します。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>JS</title> </head> <body> <button id="btn">クリック!</button> <script> document.addEventListener('DOMContentLoaded', function() { var Counter = function(elem) { this.count = 0; this.elem = elem; elem.addEventListener('click', function() { this.count++; this.show(); }); }; Counter.prototype.show = function() { console.log(this.elem.id + 'は' + this.count + '回クリックされました'); } var c = new Counter(document.getElementById('btn')); }); </script> </body> </html>
現状、上記のコードでボタンをクリックすると、
Uncaught TypeError: this.show is not a function
at HTMLButtonElement.<anonymous>
というエラーが出ます。
本によると、アロー関数にすると解決するとあり、実際機能します。
elem.addEventListener('click', () => { this.count++; this.show(); });
しかし同時に、bindメソッドを利用しても解決すると書いてあり、その方法を知りたいです。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/09 11:52