ブレイクスルーjavascriptを読んでいて分からなかったところをメモ
分からなかったコード
Modal.$parents.on("click", "a" , function(e) {
Modal.show(e);
return false;
});
Modal.prototype.show = function(e) {
var $target = $(e.currentTarget),
src = $target.attr("href");
this.$contents.html("<img src=\"" + src + "\" />");
this.$container.fadeIn();
this.$overlay.fadeIn();
//ここが分からなかった
var index = $target.data("index");
this.countChange = this.createCounter(index, this.$el.length);
return false;
};
Modal.prototype.createCounter = function(index, len){
return function(num) {
//indexは何故値が保持されるのか?
//Modal.prototype.showの中のindexを更新しているのか?
return index = (index + num + len) % len;
};
};
Modal.prototype.next = function() {
this.slide(this.countChange( 1 ));
};
コメントに書いてある感じでかなり悩んだ。。。
分かればかなり簡単!!
引数もクロージャになる!それが答え!
return function(num){}の中のindexはModal.prototype.showのindexとは別物!!
値渡しされているだけ!!
下記がその例!
function multiplyer( numA ) {
//ここでnumAが定義されていると考えればいい
return function( numB ) {
return numA = numA * numB;
}
}
var $double = multiplyer( 2 ); // 2倍にする
console.log($double(5)); //10
console.log($double(5)); //50(10*5)
console.log($double(5)); //250(50*5)