Java Reference
In-Depth Information
Prototypal Inheritance
JavaScript uses a prototypal inheritance model. To see how this works, let's make a con-
structor function for creating turtles:
var Turtle = function(name) {
this.name = name;
this.sayHi = function() {
return "Hi dude, my name is " + this.name;
}
}
This can then be used to create a new turtle instance:
var leo = new Turtle("Leonardo");
<< {"name": "Leonardo", "sayHi": function () {
return "Hi dude, my name is " + this.name;
}}
The variable leo points to an instance of the Turtle constructor. It has a name property
and a sayHi() method that refers to the name property:
leo.name;
<< "Leonardo"
leo.sayHi();
<< "Hi dude, my name is Leonardo"
The Prototype Object
In the last chapter we saw that functions have properties and methods. All functions have a
prototype property that returns an object, which is initially empty:
Turtle.prototype;
<< {}
 
Search WWH ::




Custom Search