2018-10-12 15:37:13 -04:00
---
title: Use Closure to Protect Properties Within an Object from Being Modified Externally
---
2019-07-24 00:59:27 -07:00
# Use Closure to Protect Properties Within an Object from Being Modified Externally
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
Just like in the example given, rather than declaring the `weight` variable with the `this` keyword, the `let` keyword must be used to declare it as a private variable. This way it can only be accessed inside the `Bird` function. The `getWeight` method must then be added inside the `Bird` function to access the `weight` variable.
2019-07-24 00:59:27 -07:00
---
## Solutions
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
```javascript
2018-10-12 15:37:13 -04:00
function Bird() {
let weight = 15;
2019-07-24 00:59:27 -07:00
2018-10-12 15:37:13 -04:00
this.getWeight = function() {
return weight;
};
}
```
2019-07-19 17:03:21 -04:00
2019-07-24 00:59:27 -07:00
< / details >
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2019-07-19 17:03:21 -04:00
In ES6 syntax we can make the function a bit less verbose:
```
function Bird() {
let weight = 15;
this.getWeight = () => weight;
}
```
2019-07-24 00:59:27 -07:00
< / details >