- In the previous post,
bird
had a public propertyname
. It is considered public because it can be accessed and changed outside ofbird
's definition.
bird.name = "Duffy";
Therefore, any part of your code can easily change the name of
bird
to any value. Think about things like passwords and bank accounts being easily changeable by any part of your codebase. That could cause a lot of issues.The simplest way to make this public property private is by creating a variable within the constructor function. This changes the scope of that variable to be within the constructor function versus available globally. This way, the variable can only be accessed and changed by methods also within the constructor function.
function Bird() {
let weight = 15;
this.getWeight = function() {
return weight;
}
}
let ducky = new Bird();
console.log(ducky.getWeight()); // will display 15
- Here
getWeight
is a privileged method, because it has access to the private variableweight
. This is possible becauseweight
is declared in the same context asgetWeight
. In JavaScript, a function always has access to the context in which it was created. This is calledclosure
.
Top comments (0)