I'll admit I'm flailing around, cobbling code together from different authors in an attempt to figure out javascript prototypes.
I'm new to the prototype concept, and would like to have some instance variables in my class that can be modified using a method.
Here's what I'm trying, in essence. This was cribbed and modified from the web:
var MyGlobe = function () {
var self = this;
self.variable1 = null;
return self;
}
MyGlobe.prototype = function () {
var setup = function () {
this.variable1 = 33;
};
return {
setup:setup
};
}();
...the point of all that is so I can call the setup
method on an instance of MyGlobe
and set variable1
properly:
var aGlobe = new MyGlobe();
aGlobe.setup();
//aGlobe.variable1 is 33 now
This actually seems to work, but I'm not sure why the original author did things this way? For instance, what's the point of the self.variable1
bit at the beginning?
Is it preferable to typing out:
MyGlobe.prototype.variable1;
MyGlobe.prototype.variable2;
//....
I also thought you'd do something like self=this
if you thought your class would be used in a callback function for example, but that doesn't appear to be the case here? (Happy to be shown wrong.)
I'm not sure what the best practices are here and would like to know more.