とある参考書にてJavaScriptの勉強をしているうちに、どのどうな挙動をしているのかわからなくなってしまったので質問させてください。
スクリプトは以下の通りです。
※長くて申し訳ありません
JavaScript
1function Modal(el) { 2 this.initialize(el); 3} 4 5Modal.prototype.initialize = function(el) { 6 this.$el = el; 7 this.$container = $("#modal"); 8 this.$contents = $("#modal-contents"); 9 this.$close = $("#modal-close"); 10 this.$next = $("#modal-next"); 11 this.$prev = $("#modal-prev"); 12 this.$overlay = $("#modal-overlay"); 13 this.$window = $(window); 14 this.handleEvents(); 15}; 16 17Modal.prototype.handleEvents = function() { 18 var self = this; 19 this.$el.on("click", function(e) { 20 self.show(e); 21 return false; 22 }); 23 24 this.$overlay.on("click", function(e) { 25 self.hide(e); 26 return false; 27 }); 28 29 this.$close.on("click", function(e) { 30 self.hide(e); 31 return false; 32 }); 33 34 this.$next.on("click", function(e) { 35 self.next(e); 36 return false; 37 }); 38 39 this.$prev.on("click", function(e) { 40 self.prev(e); 41 return false; 42 }); 43}; 44 45Modal.prototype.show = function(e) { 46 var $target = $(e.currentTarget), 47 src = $target.attr("href"); 48 this.$contents.html("<img src=\"" + src + "\" />"); 49 this.$container.fadeIn(); 50 this.$overlay.fadeIn(); 51 var index = $target.data("index"); 52 this.countChange = this.createCounter(index, this.$el.length); // ① 53 return false; 54}; 55 56Modal.prototype.hide = function(e) { 57 this.$container.fadeOut(); 58 this.$overlay.fadeOut(); 59}; 60 61Modal.prototype.slide = function(index) { 62 this.$contents.find("img").fadeOut({ 63 complete: function() { 64 var src = $("[data-index=\"" + index + "\"]").find("img").attr("src"); 65 $(this).attr("src", src).fadeIn(); 66 } 67 }); 68}; 69 70// ② 71Modal.prototype.countChange = function(num, index, len) { 72 return (index + num + len) % len; 73}; 74 75// ③ 76Modal.prototype.createCounter = function(index, len) { 77 return function(num) { 78 return index = (index + num + len) % len; 79 }; 80}; 81 82Modal.prototype.next = function() { 83 this.slide(this.countChange(1)); 84}; 85 86Modal.prototype.prev = function() { 87 this.slide(this.countChange(-1)); 88}; 89 90var modal = new Modal($("#modal-thumb a"));
これはモーダルとして正常に機能するのですが、
画像をタップするとshow関数が呼ばれて①から③が動くのですが、この時点では
javascript
1return function(num) { 2 return index = (index + num + len) % len; 3};
の引数のnumはわたってきていません。
next、prevボタンが押されると、それぞれnext,prev関数が機能してnumに1か-1が渡ってきます。
わからないのが、
まず③でreturnでfunctionしている意味、また、単に
javascript
1return index = (index + num + len) % len;
だけではいけない理由。
それと、①で
javascript
1this.countChange = this.createCounter(index, this.$el.length)
としているなかで、どのタイミングでnumが渡っていくのか。
自分的に理解が及ばず質問が抽象的になってしまっており申し訳ありませんが、
ご教示いただけたら幸いです。よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。