teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

handleEventでのthisの参照先変更

2019/11/15 07:13

投稿

Ryu__ta
Ryu__ta

スコア15

title CHANGED
File without changes
body CHANGED
@@ -3,6 +3,8 @@
3
3
  class構文の練習しているのですが、どこが問題なのかわからず...
4
4
  nect,prevのボタンを押すと画像が切り替わる処理です。
5
5
 
6
+ ⇒ handleEventでのthisの参照先変更
7
+
6
8
  ### 発生している問題・エラーメッセージ
7
9
 
8
10
  ```

1

handleEventでのthisの参照先変更

2019/11/15 07:13

投稿

Ryu__ta
Ryu__ta

スコア15

title CHANGED
File without changes
body CHANGED
@@ -65,44 +65,55 @@
65
65
 
66
66
  class Photoview {
67
67
 
68
- constructor(){
68
+ constructor( init_index = 0 ){
69
69
  this.$el = $('.image_wrapper img');
70
+ this.images = [
70
- this.images = [ 'https://fakeimg.pl/350x200/ff0000/?text=1',
71
+ 'https://fakeimg.pl/350x200/ff0000/?text=1',
71
72
  'https://fakeimg.pl/350x200/ff0000/000?text=2',
72
- 'https://fakeimg.pl/350x200/ff0000,128/000,255?text=3'];
73
+ 'https://fakeimg.pl/350x200/ff0000,128/000,255?text=3'
74
+ ];
73
75
  this.$nextBtn = $('.next');
74
76
  this.$prevBtn = $('.prev');
75
- this.index = 0
77
+ this.index = init_index;
76
78
  this.handleEvent();
77
79
  this.displayImg();
78
80
  }
79
81
 
82
+ get Index() {
83
+ return this.index;
84
+ }
85
+
86
+ set Index( v ) {
87
+ this.index = v;
88
+ }
89
+
80
90
  handleEvent() {
91
+ const self = this;
81
92
  this.$nextBtn.on("click", function(){
82
- this.next();
93
+ self.next( self.Index );
83
94
  });
84
95
  this.$prevBtn.on("click", function(){
85
- this.prev();
96
+ self.prev();
86
97
  });
87
98
  }
88
99
 
89
- next( index ) {
100
+ next() {
90
- this.index++
101
+ this.index++;
91
- this.displayImg( index )
102
+ this.displayImg( this.Index );
92
103
  }
93
104
 
94
- prev( index ) {
105
+ prev() {
95
- this.index--
106
+ this.index--;
96
- this.displayImg( index )
107
+ this.displayImg( this.Index );
97
108
  }
98
109
 
99
- displayImg( index ) {
110
+ displayImg() {
100
- this.$el.attr( 'src', this.images[ index ] );
111
+ this.$el.attr( 'src', this.images[ this.Index ] );
101
112
  }
102
113
 
103
114
  }
104
115
 
105
- const Photoview_ins = new Photoview;
116
+ const Photoview_ins = new Photoview();
106
117
 
107
118
  </script>
108
119