myObject.prototype in ECMAScript 262
The prototype for a class.
- Property Type
- Object
This property is read-only for intrinsic JS classes (e.g. the Date
object) but may be re-assigned for user-defined classes.
While the prototype
property is 'read-only' for intrinsic classes, it may be used to extend their functionality. For example the following code uses the prototype
property of the Number
object to extend all numbers to support a custom 'truncate' method:
Number.prototype.trunctate=function(){
return this>0?Math.floor(this):Math.ceil(this);
}
var x=12.37;
var y=-12.37;
x = x.truncate(); // ** 12
y = y.truncate(); // ** -12
The following code sample shows how to use the prototype
property to cause one class to inherit from another:
function Mammal(name){
this.name=name;
this.offspring=[];
}
Mammal.prototype.haveABaby=function(){
var newBaby=new this.constructor("Baby "+this.name); //Uses Cat for cats, Mammal for Mammals
this.offspring.push(newBaby);
return newBaby;
}
Mammal.prototype.toString=function(){
return '[Mammal "'+this.name+'"]';
}
Cat.prototype = new Mammal; // Here's where the inheritance occurs
Cat.prototype.constructor=Cat; // Otherwise instances of Cat would have a constructor of Mammal
function Cat(name){
this.name=name;
}
Cat.prototype.toString=function(){
return '[Cat "'+this.name+'"]';
}
var msg;
var someAnimal = new Mammal('Mr. Biggles');
msg = 'someAnimal is '+someAnimal; // ** 'someAnimal is [Mammal "Mr. Biggles"]'
var myPet = new Cat('Felix');
msg = 'myPet is '+myPet; // ** 'myPet is [Cat "Felix"]'
myPet.haveABaby(); // calls a method inherited from Mammal
msg = myPet.offspring.length; // ** 1
msg = "First baby is "+myPet.offspring[0]; // ** 'First baby is [Cat "Baby Felix"]'