I've recently begin delving much more into JavaScript and have realized that what I thought I knew before was not very much. That being said, I've programmed some Java so naturally when I came to JavaScript I wanted to understand how to create objects.
As I dug, I came across two different ways to declare methods and fields for all objects. One of them is to declare them in the constructor:
[colorcode=JavaScript]
function ExampleObject() {
this.aField = "";
this.method = function(param) {
alert(param);
}
}
[/colorcode]
Another, that I think accomplishes the same thing, is to use prototype:
[colorcode=JavaScript]
function ExampleObject() {}
//this would have to be defined outside of the constructor, in this case
ExampleObject.prototype.aField = "";
ExampleObject.prototype.method = function(param) {
alert(param);
}
[/colorcode]
Now, please bear with me as a launch an onslaught of questions, as I've only been nursing my understanding for a couple days now:
1) Do these two code snippets accomplish the same thing? If not, what is the difference and why does it occur? If so, is one way better, faster, or more universally accepted?
2) Does using prototype retain the reference of the this keyword? In other words, if I referred to "this.aField" in the prototype method declaration, would JavaScript know to refer to an ExampleObject's "aField" field?
...and I think I'll stop there...