回答編集履歴
2
変数 wordlist1, wordlist2 を追記
test
CHANGED
@@ -13,6 +13,10 @@
|
|
13
13
|
例えば、下記2つのコードは等価です。
|
14
14
|
|
15
15
|
```javascript
|
16
|
+
'use strict';
|
17
|
+
const wordlist1 = {'あ': 1, 'い': 2, 'う': 3, 'え': 4, 'お': 5};
|
18
|
+
const wordlist2 = {'あ': 'a', 'い': 'b', 'う': 'c', 'え': 'd', 'お': 'e'};
|
19
|
+
|
16
20
|
(function () {
|
17
21
|
let selectword = ['あ', 'い', 'う'];
|
18
22
|
|
1
束縛とは
test
CHANGED
@@ -2,6 +2,36 @@
|
|
2
2
|
|
3
3
|
this値の束縛は「早いもの勝ち」です。
|
4
4
|
アロー関数でthis値を**束縛**した後に、`Array.prototype.map()`の第二引数でthis値を**束縛し直すことはできません**。
|
5
|
+
|
6
|
+
---
|
7
|
+
|
8
|
+
ここでいう「束縛」とは「外部から関数コード内で使用する値を固定する挙動」を指します。
|
9
|
+
`Function.prototype.bind()` でも「this値を束縛」することが可能です。
|
10
|
+
|
11
|
+
- [Function\.prototype\.bind\(\) \- JavaScript \| MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)
|
12
|
+
|
13
|
+
例えば、下記2つのコードは等価です。
|
14
|
+
|
15
|
+
```javascript
|
16
|
+
(function () {
|
17
|
+
let selectword = ['あ', 'い', 'う'];
|
18
|
+
|
19
|
+
const result1 = selectword.map(value => this[value], wordlist1);
|
20
|
+
const result2 = selectword.map(function (value) { return this[value]; }.bind(wordlist2), wordlist1);
|
21
|
+
|
22
|
+
console.log(result1); // 出力結果:['a', 'b', 'c']
|
23
|
+
console.log(result2); // 出力結果:['a', 'b', 'c']
|
24
|
+
}).call(wordlist2);
|
25
|
+
```
|
26
|
+
|
27
|
+
アロー関数はいったん忘れて、call, apply, bindあたりの挙動を追いかけてみると、見えるものがあるかもしれません。
|
28
|
+
|
29
|
+
```javascript
|
30
|
+
'use strict';
|
31
|
+
const sample = function sample () { console.log(this); };
|
32
|
+
sample.bind(1).call(2); // 1
|
33
|
+
sample.bind(1).apply([3]); // 1
|
34
|
+
```
|
5
35
|
|
6
36
|
### 解決方法
|
7
37
|
|