-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprototype.js
More file actions
35 lines (29 loc) · 891 Bytes
/
Copy pathprototype.js
File metadata and controls
35 lines (29 loc) · 891 Bytes
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
// 1. CONSTRUCTOR FUNCTION
// Defines properties unique to each instance
function Robot(name, type) {
this.name = name;
this.type = type;
this.energy = 100;
}
// 2. PROTOTYPE METHODS
// Shared methods defined once to save memory
Robot.prototype.introduce = function() {
return `ID: ${this.name} | Unit: ${this.type}`;
};
Robot.prototype.work = function() {
if (this.energy > 0) {
this.energy -= 10;
return `${this.name} is working... Energy: ${this.energy}%`;
}
return `${this.name} is out of battery!`;
};
// 3. CREATING INSTANCES
const alpha = new Robot("Alpha-1", "Miner");
const beta = new Robot("Beta-7", "Builder");
// 4. USAGE
console.log(alpha.introduce());
console.log(beta.introduce());
console.log(alpha.work());
console.log(alpha.work());
// Checking memory efficiency
console.log(alpha.introduce === beta.introduce); // true