LoginSignup
3
2

More than 5 years have passed since last update.

引数がクロージャーになる

Last updated at Posted at 2017-02-16

ブレイクスルー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)
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2