-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_obj_prop_priv.js
62 lines (47 loc) · 1.64 KB
/
js_obj_prop_priv.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
/*
MAKE OBJECT PROPERTIES PRIVATE
Objects have their own attributes, called properties, and their own functions,
called methods.
In the previous challenges, we used the this keyword to reference public properties
of the current object.
We can also create private properties and private methods, which aren't accessible
from outside the object.
To do this, we create the variable inside the constructor using the var keyword we're
familiar with, instead of creating it as a property of this.
This is useful for when we need to store information about an object but we want to
control how it is used by outside code.
For example, what if we want to store the speed our car is traveling at but we only
want outside code to be able to modify it by accelerating or decelerating, so the
speed changes in a controlled way?
In the editor you can see an example of a Car constructor that implements this pattern.
Now try it yourself! Modify the Bike constructor to have a private property called
gear and two public methods called getGear and setGear to get and set that value.
*/
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
var Bike = function() {
// Only change code below this line.
var gear = 4;
this.getGear = function () {
return gear;
};
this.setGear = function (gr) {
gear = gr;
};
};
var myCar = new Car();
var myBike = new Bike();
myBike.setGear(10);
console.log("The Bike I built: ", myBike.getGear());