forked from GrosSacASac/JavaScript-Set-Up
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass7.js
More file actions
83 lines (62 loc) · 2.25 KB
/
Copy pathclass7.js
File metadata and controls
83 lines (62 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* Function based classes importable as namespaces
good:
* clean syntax
* no new , no this
* no side effect
* no prototype, instances do not carry a prototype chain
* compose and inherit
* constructor function are pure
* compatible with object pools
* scales well
* methods can be pure functions or mutating functions
* you can store the methods in other variables, because it doesn't depend on the this
* compatible with higher-order functions
* explicit hierarchies
* class methods and instance custom function member are explicitly different in the calling program
* can be transferred as JSON over the network with no additional overhead
* also compatible with Web Worker / local storage by default
* treeshake friendly
* best possible minification
bad:
* Is not a widely used technique
to recognize that an instance is from a particular Object we can add the is function to the class.
It can check all required properties or an agreed-upon _is field.
*/
export { createPlayer, toString, createUnfairPlayer, unfairPlayerToString };
/* import as a nameSpace:
import * as Player from "./Player.js";
const player = Player.create({ ... });
const string = Player.toString(player);
*/
const create = function (constructorParameters) {
//no privates
const { name, hitPoints } = constructorParameters;
const experience = 0; // default value
const printCounter = 0;
return {
name,
hitPoints,
experience,
printCounter
};
};
const toString = function (player) { // explicit instance parameter
player.printCounter += 1;
return `\n${player.name}\n${player.hitPoints}\n${player.experience}
toStringCall = ${player.printCounter}`;
};
const createUnfairPlayer = function (constructorParameters) {
const thisPlayer = create(constructorParameters);
thisPlayer.hitPoints *= 2;
return thisPlayer;
};
const unfairPlayerToString = function (unfairPlayer) {
return "Warning, unfair:" + toString(unfairPlayer);
};
const player1 = create({ name: "Gru", hitPoints: 100 });
console.log(toString(player1));
player1.hitPoints += -50;
console.log(toString(player1));
const player2 = createUnfairPlayer({ name: "Lord Zoo", hitPoints: 100 });
console.log(unfairPlayerToString(player2));
player2.hitPoints += 20;