回答編集履歴
1
追記
test
CHANGED
@@ -1,4 +1,94 @@
|
|
1
1
|
> インターフェースは実現できますか?
|
2
|
+
|
3
|
+
|
4
|
+
|
5
|
+
# Object.setPrototypeOf()
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
回答済みとなって久しいご質問でしたが、追記になります。
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
[DOM Standard](https://dom.spec.whatwg.org/)の ``IDL`` に ``interface mixin`` と示される実装を class ブロック構文でどのように実現しているのかを探っていたところ、``Object.setPrototypeOf()`` を利用すれば、以下のように、「振る舞い」を 別の class ブロックで定義できるようです。
|
14
|
+
|
15
|
+
|
16
|
+
|
17
|
+
```javascript
|
18
|
+
|
19
|
+
class AnyInterface {
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
increment() {
|
24
|
+
|
25
|
+
this.data++;
|
26
|
+
|
27
|
+
}
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
decrement() {
|
32
|
+
|
33
|
+
this.data--;
|
34
|
+
|
35
|
+
}
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
}
|
40
|
+
|
41
|
+
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
class MyClass {
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
constructor ( data = 0 ) {
|
50
|
+
|
51
|
+
this.data = data;
|
52
|
+
|
53
|
+
}
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
}
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
// mixin interface を実現?
|
62
|
+
|
63
|
+
Object.setPrototypeOf( MyClass.prototype, AnyInterface.prototype );
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
// test
|
68
|
+
|
69
|
+
let myClass = new MyClass( 3 );
|
70
|
+
|
71
|
+
console.log( myClass.data ); // 3
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
myClass.increment();
|
76
|
+
|
77
|
+
console.log( myClass.data ); // 4
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
myClass.decrement();
|
82
|
+
|
83
|
+
console.log( myClass.data ); // 3
|
84
|
+
|
85
|
+
```
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
----
|
90
|
+
|
91
|
+
以下、古い回答になります。
|
2
92
|
|
3
93
|
|
4
94
|
|