forked from GrosSacASac/JavaScript-Set-Up
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass2.js
More file actions
64 lines (50 loc) · 1.58 KB
/
Copy pathclass2.js
File metadata and controls
64 lines (50 loc) · 1.58 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
/* --Constructor with Prototypes--
good:
* shared methods are created only once, even for subclasses
bad:
* uses this and new --> danger
* prototype side effects
*/
export { Player, UnfairPlayer };
const Player = function (spec) {
//private member
//secret is only accessible later if you create
//links to it in this scope now
const secret = {};
//public members
this.name = spec.name;
this.hitPoints = spec.hitPoints;
this.experience = 0; //default value
this.printCounter = 0;
};
//Put in the prototype everything that is and stays the same for all instances
Player.prototype = {
toString: function () {
this.printCounter += 1;
return `\n${this.name}\n${this.hitPoints}\n${this.experience}
toStringCall = ${this.printCounter}`;
}
};
const UnfairPlayer = function (spec) {
Player.call(this, spec); // call super constructor.
//modify property
this.hitPoints *= 2;
//add property
this.cheater = true;
};
//inherit all methods from Player
//Note that changing UnfairPlayer.prototype will not change Player.prototype
UnfairPlayer.prototype = Object.create(Player.prototype);
UnfairPlayer.prototype.toString = function () {
return "Warning, unfair:" + Player.prototype.toString.apply(this);
};
// Create:
const player1 = new Player({ name: "Gru", hitPoints: 100 });
// Use:
console.log(player1.toString());
player1.hitPoints += -50; //ouch !
console.log(player1.toString());
// Create:
const player2 = new UnfairPlayer({ name: "Lord Zoo", hitPoints: 100 });
// Use:
console.log(player2.toString());