Let's say I have a constructor Alpha:
//[#1]
Alpha = function(a,b){
attrib1 = a;
attrib2 = b;
};
attrib1 and attrib2 should have a different value for every different instance.
The usual solution would be to switch attrib1 and attrib2 with this.attrib1 and this.attrib2, however since we are inside the constructor there is no object yet and calling this would make little sense (I know that most browsers would probably accept it anyway, but that's not the point).
First question: are attrib1 and attrib2 (as shown in the example) local to the constructor? I'm pretty new to Javascript and its prototype system.
My solution would be:
//[#2]
Alpha = function(a,b){
attrib1 = a;
attrib2 = b;
};
Alpha.attrib1 = undefined;
Alpha.attrib2 = undefined;
But then, how does the constructor know that I'm referring to the object's attributes and not some local variables called attrib1 and attrib2, since I'm declaring the constructor before the attributes? Wouldn't this solution be bad because I should declare the attributes as Alpha.prototype.attrib1 and Alpha.prototype.attrib2 since they are common to all Alpha objects and don't need to be declared more than once? I'm aware that object literals could be a workaround but I don't want to use them. If I referred to "class" variables, like this:
//[#3]
Alpha = function(a,b){
Alpha.attrib1 = a;
Alpha.attrib2 = b;
}
What would happen? Normally, it would change the class value of attrib1 and attrib2, but since in JS classes are already objects wouldn't that be equivalent to my example #1, with the difference that every instance of Alpha will start with attrib1 and attrib2 set to whatever the previous constructor set them? Or maybe only members declared as Alpha.prototype.attrib would do that, since it's the prototype that gets copied?
I'm normally a C++ programmer and I'm sorry if it's a dumb question, however I'd like to know more about it before I write anything too massive with JS. Thanks for reading.