Java Reference
In-Depth Information
Own Properties and Prototype Properties
In the previous example, the object
raph
had a
name
property that it inherited from the
constructor function and a
weapon
property that it inherited from the prototype property.
The object
raph
has access to both these properties, but the
name
property is considered
to be its
own
property while the
weapon
property is inherited from the prototype object.
Every object has a
hasOwnProperty()
method that can be used to check if a method is
its own property, or is inherited from the prototype:
raph.hasOwnProperty('name');
<< true
raph.hasOwnProperty('weapon');
<< false
So what's the difference between own properties and prototype properties? Prototype prop-
erties are shared by
every
instance of the
Turtle
constructor function. This means that
they'll all have a
weapon
property and it will always be the same value. If we create an-
other instance of the
Turtle
constructor, we'll see that it also inherits a
weapon
property
that has the same value of
"Hands"
:
var don = new Turtle("Donatello");
<< {"attack": function (){
return this.name + " hits you with his " + this.weapon;
}, "name": "Donatello", "sayHi": function () {
return "Hi dude, my name is " + this.name;
}, "weapon": "Hands"
don.weapon;
<< "Hands"
Every time an instance of the
Turtle
constructor function calls the
weapon
property, it
will return
"Hands"
. This value is the same for all the instances and only exists in one
placeāas a property of the prototype object. This means that it only exists in memory in
one place, which is more efficient than each instance having its own value. This is particu-
larly useful for any properties that are the same.
