I'm trying to get my head around this black art called JavaScript - and, I must admit, pretty excited about it. I've been looking at code examples, mainly from "easeljs" since that is what I will be using mainly. And I'm a bit confused..
I (think I) understand the difference between using the prototype
for functions or properties that are class
variables and using this.someProp
for 'instance' variables (Yes, I understand that there are no classes in JavaScript.)
The code I have looked at, and am using as templates for my own code, declare
prototype
variables and then refers to them with this i.e.
In the constructor:
this.name = name;
Then a declaration:
Object.prototype.name;
And later,
this.name = "Freddy";
This is within functions called with 'new' so in this case, as I understand it, this
refers to the current object. What puzzles me is what the prototype declaration is doing and why do we use it for instance variables?
Clarification: In the following code, I don't see what the prototype declaration of radius is achieving:
(function(){
// constructor
function MyCircle(radius){
this.radius = radius;
}
MyCircle.prototype.radius;
this.area = function(){
return 3.14*this.radius*this.radius;
};
window.MyCircle = MyCircle;
}());