I realize this has been asked hundreds of times, however, I can't seem to grasp the concept of "why" prototypes in JavaScript are proper, as apposed to imitating classes (yes, I know JavaScript is a prototypical based language - I've gathered that much).
Like many other people striving to make JavaScript an everyday language that I use, I'm use to the regular OOP class style, as I've played around in Java (and used classes in ActionScript as well as PHP). However, while I think I understand how prototypes work, I can't seem to understand why they're needed.
Here's my sample script of how I'm currently understanding prototypes in JavaScript:
var Apple = function() { // An apple? }; Apple.prototype.color = "red"; Apple.prototype.changeColor = function(new_color) { this.color = new_color; }; Apple.prototype.getColor = function() { alert('color: '+this.color); }; var apple1 = new Apple(); var apple2 = new Apple(); apple2.changeColor("green"); apple1.getColor(); apple2.getColor(); ...I had assumed that maybe the prototype meant that it shared the same object instead of just creating a new object each time - however, it obviously isn't the case since both apple1 and apple2 have different colors, still (after running said script).
Then I wrote it in what's more of a object-oriented script:
var Apple = function() { this.color = "red"; this.changeColor = function(new_color) { this.color = new_color; }; this.getColor = function() { alert('color: '+this.color); }; }; var apple1 = new Apple(); var apple2 = new Apple(); apple2.changeColor("green"); apple1.getColor(); apple2.getColor(); With the exact same results (as expected). ...Why is the latter code not recommended? I have no problem using prototypes (assuming I used them correctly), but I need to understand the concept of "why".
...Any help?