回答編集履歴
1
コンストラクタパターンのコード追記
test
CHANGED
@@ -12,6 +12,86 @@
|
|
12
12
|
|
13
13
|
あるいは、型付言語的な仕組みが欲しいという事なのでしょうか。
|
14
14
|
|
15
|
+
|
16
|
+
|
17
|
+
```JavaScript
|
18
|
+
|
19
|
+
'use strict';
|
20
|
+
|
21
|
+
function User (name, id, position) {
|
22
|
+
|
23
|
+
this.name = String(name);
|
24
|
+
|
25
|
+
this.id = Number(position);
|
26
|
+
|
27
|
+
this.position = Number(position);
|
28
|
+
|
29
|
+
}
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
function Box ( /*arrayLike*/ ) {
|
34
|
+
|
35
|
+
if (arguments.length) {
|
36
|
+
|
37
|
+
var arrayLike = Object(arguments[0]);
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
for (var i = 0, len = arrayLike.length, user; i < len; ++i) {
|
42
|
+
|
43
|
+
if (Object.prototype.hasOwnProperty.call(arrayLike, i)) {
|
44
|
+
|
45
|
+
user = arrayLike[i];
|
46
|
+
|
47
|
+
this.add(user.name, user.id, user.position);
|
48
|
+
|
49
|
+
}
|
50
|
+
|
51
|
+
}
|
52
|
+
|
53
|
+
}
|
54
|
+
|
55
|
+
}
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
Object.defineProperty(Box.prototype, 'add', {
|
60
|
+
|
61
|
+
writable: true,
|
62
|
+
|
63
|
+
enumerable: false,
|
64
|
+
|
65
|
+
configurable: true,
|
66
|
+
|
67
|
+
value: function add (name, id, position) {
|
68
|
+
|
69
|
+
return Array.prototype.push.call(this, new User(name, id, position));
|
70
|
+
|
71
|
+
}
|
72
|
+
|
73
|
+
})
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
var box1 = new Box();
|
78
|
+
|
79
|
+
box1.add('taro', 1, 0);
|
80
|
+
|
81
|
+
box1.add('koichi', 2, 100);
|
82
|
+
|
83
|
+
console.log(box1);
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
var box2 = new Box([{name: 'taro', id: 1, position: 0}, {name: 'koichi', id: 2, position: 100}]);
|
88
|
+
|
89
|
+
console.log(box2);
|
90
|
+
|
91
|
+
```
|
92
|
+
|
93
|
+
|
94
|
+
|
15
95
|
「seriさんがどういう設計を望んでいるのか」を日本語で書き表してみて下さい。
|
16
96
|
|
17
97
|
また、seriさんの分かる範疇でJavaScriptコードを書き、「コード上で足りない部分」を説明してみて下さい。
|