what are the difference between these two ways of creating a class:
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
function Apple (type) {
this.type = type;
this.color = "red";
this.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
}
and how do you instantiate and use the members?
While JavaScript is an object-oriented language, it does not use classes. You don’t create a “class” in JavaScript. You create a “prototype”. JavaScript is considered a Prototype-based language.
The first example is known as “object-literal notation” for creating an object (a subset of which is popularly known as JSON). An analogy to this in class-based languages is a “static” class, in the sense that you don’t need to create a new instance of an object in this case; It “just exists”, once you define it. You wouldn’t instantiate it, you’d access members of
appleimmediately sinceappleis already an object. It is also similar to creating an anonymous class in Java. You’d use it like this:With the second example, you’re creating a prototype (not a class), which can be used to instantiate objects of type
Apple. You could use it like this:JavaScript allows you to modify and add to an object’s prototype, so after you declared your
Appleprototype, you could still continue to add or change things about it like this:When you do this, all objects derived from the
Appleprototype will gain asizefield. This is the basis for how the PrototypeJS framework works to modify native JavaScript objects to add & fix functionality.Keep in mind that it is considered bad practice to modify the prototype of native JavaScript objects, so you should avoid doing it whenever possible.