Created
September 10, 2012 05:12
-
-
Save rikwatson/3688990 to your computer and use it in GitHub Desktop.
Javascript prototype example (Which you've seen 100's of times)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Constructor. <em>this</em> is returned as new object and its | |
// internal [[prototype]] property will be set to the constructor's | |
// default prototype property. | |
// | |
var Circle = function(radius) | |
{ | |
this.radius = radius; | |
// Next line is implicit, added for illustration only. | |
// | |
// this.__proto__ = Circle.prototype; | |
} | |
// augment Circle's default prototype property thereby augmenting | |
// the prototype of each generated instance | |
// | |
Circle.prototype.area = function() | |
{ | |
return Math.PI*this.radius*this.radius; | |
} | |
// create two instances of a circle and make each leverage | |
// the common prototype | |
// | |
var a = new Circle(3), b = new Circle(4); | |
a.area().toFixed(2); // 28.27 | |
b.area().toFixed(2); // 50.27 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment