-
Notifications
You must be signed in to change notification settings - Fork 102
/
Constructor.js
42 lines (34 loc) · 1013 Bytes
/
Constructor.js
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
/*
Constructors are special function that can be used to instantiate new objects with methods and properties defined by that function.
Constructor pattern is the most commonly used pattern in JavaScript for creating new objects of similiar kind.
*/
// traditional Function-based syntax
/*
function Hero(name, specialAbility) {
// setting property values
this.name = name;
this.specialAbility = specialAbility;
// declaring a method on the object
this.getDetails = function() {
return this.name + ' can ' + this.specialAbility;
};
}
*/
// ES6 Class syntax
class Hero {
constructor(name, specialAbility) {
// setting property values
this._name = name;
this._specialAbility = specialAbility;
// declaring a method on the object
this.getDetails = function() {
return `${this._name} can ${this._specialAbility}`;
};
}
}
// creating new instances of Hero
/*
const IronMan = new Hero('Iron Man', 'fly');
console.log(IronMan.getDetails()); // Iron Man can fly
*/
module.exports = Hero;