-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-literal-objects-and-prototypes-in-js.js
66 lines (61 loc) · 1.86 KB
/
03-literal-objects-and-prototypes-in-js.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Here is a Literal Object
const natalia = {
name: 'Natalia',
age: 20,
approvedCourses: ['Definitive HTML & CSS Course'],
//approveCourse: function() {}
approveCourse (newCourse) {
//use of 'this' to refers to this object
this.approvedCourses.push(newCourse)
}
}
// The way we add a method to an literal object:
natalia.approveCourse('Css Grid Course')
console.log(natalia);
/*
{ name: 'Natalia',
age: 20,
approvedCourses: [ 'Definitive HTML & CSS Course', 'Css Grid Course' ],
approveCourse: [Function: approveCourse]
}
*/
// Changes in literal object only affect to itself
// Here we create a Prototype, also known as Constructor Function
function Student(name, age, approvedCourses) {
this.name = name
this.age = age
this.approvedCourses = approvedCourses
//the code comment below makes a reference of how to create methods
// this.approveCourse = function (newCourse) {
// this.approvedCourses.push(newCourse)
// }
}
//Remember the prototype keyword is necessary to add new properties and methods to Prototypes.
Student.prototype.approveCourse = function (newCourse) {
this.approvedCourses.push(newCourse)
}
//Creation of an instance called juanita from Student prototype.
const juanita = new Student('Juanita Alejandra', 15, ['VideoGames Production Intro Course', 'Character Design Course'])
console.log(juanita);
/*
Student {
name: 'Juanita Alejandra',
age: 15,
approvedCourses: [ 'VideoGames Production Intro Course', 'Character Design Course' ]
}
*/
//Methods are hidden in the __proto__ property.
// approveCourse() method was added, so we can use it.
juanita.approveCourse('Unreal Engine Course')
console.log(juanita);
/*
Student {
name: 'Juanita Alejandra',
age: 15,
approvedCourses: [
'VideoGames Production Intro Course',
'Character Design Course',
'Unreal Engine Course'
]
}
*/