Java Reference
In-Depth Information
Public and Private Methods
By default, an object's methods are
public
in JavaScript. Methods and properties are said
to be public because they can be queried directly and changed by assignment.The dynamic
nature of the language means that an object's properties and methods can be changed after it
has been created.
The
name
and
weapon
properties of our example object are said to be public:
raph.weapon
<< "Sai"
We can use the concept of variable scope to keep properties
private
and prevent them from
being changed. A
getter
method can then be used to return their values. In this example, the
Turtle()
constructor function is modified to include a private
_color
property:
function Turtle(name,color) {
this.name = name;
this.sayHi = function() {
return "Hi dude, my name is " + this.name;
}
// This property will only available inside the
constructor
↵
function
var _color = color;
this.getName = function() {
return _name;
}
this.getColor = function() {
return _color;
}
}
