Java Reference
In-Depth Information
When a new instance of the the
Turtle
object is instantiated using the
new
operator, all
the properties and methods of the prototype will be added to the new instance. Since the
prototype is just an object, we can add new properties by assignment:
Turtle.prototype.weapon = "Hands";
<< "Hands"
We can also add a method to the prototype object in a similar way:
Turtle.prototype.attack = function(){
return this.name + " hits you with his " + this.weapon;
}
<< function (){
return this.name + " hits you with his " + this.weapon;
}
Now if we create a new
Turtle
instance, we can see that it inherits the
weapon
property
and
attack()
method from the
Turtle.prototype
object, as well as receiving the
name
property and
sayHi()
method from from the constructor function:
var raph = new Turtle("Raphael");
raph.name;
<< "Raphael"
raph.sayHi();
<< "Hi dude, my name is Raphael"
raph.weapon; // inherited from the prototype
<< "Hands"
raph.attack() // inherited from the prototype
<< "Raphael hits you with his Hands"
Notice that there's a reference to
this.name
in the prototype
attack()
method, and
when the instance calls the
attack()
method, it uses the instance's
name
property. This
is because
this
in the prototype object always refers to the instance that actually calls the
method.
