-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathINTER - OBJECTS - keeping object members private.js
More file actions
52 lines (41 loc) · 1.26 KB
/
Copy pathINTER - OBJECTS - keeping object members private.js
File metadata and controls
52 lines (41 loc) · 1.26 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
/*
!!INTER - OBJECTS - KEEPING OBJECT MEMBERS PRIVATE!!
> You want to keep one or more object properties private, so they can’t be accessed outside
the object instance
*.concat() - used to join two or more arrays
*/
/*
SOLUTION:
+) When creating the private data members, do not use the this keyword with the member
*/
+)
function Tune(song, artist) {
var title = song;
this.concat = function() {
return title + " " + artist;
}
}
var happySongs = [];
happySongs[0] = new Tune("Putting on the Ritz", "Ella Fitzgerald");
// undefined
console.log(happySongs[0].title);
// prints out correct title and artist
console.log(happySongs[0].concat());
/*
EXAMPLE:
1) Be aware, though, that the privacy of the variable is somewhat illusory. One can easily
assign a value to that property outside the constructor function, and overwrite the private
data
2) Developers also typically use a naming convention where private data members begin with
an underscore, to highlight that they aren’t meant to be accessed or set directly
*/
1)
happySongs[0].title = 'testing';
console.log(happySongs[0].title); // testing
2)
function Tune(song,artist) {
var _title = song;
this.concat = function() {
return _title + " " + artist;
}
}