If you're shooting for an object oriented approach, you should be defining your functions on the prototype
chain.
function Coffee(name, roast, location) {
this.name = name;
this.roast = roast;
this.location = location;
}
Coffee.prototype.getCoffeeType = function() {
return this.name + " " + this.roast + " from " + this.location;
};
var esspresso = new Coffee("Starbuck's Esspresso Blend", "Dark", "Seattle");
var cappuccino = new Coffee(esspresso.name, "Dark", "Seattle");
document.write(cappuccino.getCoffeeType());
The code above will have the following effects:
function Coffee(...)
is the class's main constructor.
Coffee.prototype.getCoffeeType
is a function that each instance of the Coffee
class will have. This function will be able to access the this
variables of the class (the class members).
esspresso
and cappuccino
are instances of the Coffee
class, instantiated somewhere in program code (outside of the class definition / constructor / prototype functions).
You can then call functions defined on the class's prototype chain on these instance objects.
The output of the above code will give you "Starbuck's Esspresso Blend Dark from Seattle"
Note that the additional benefit of defining a function on the prototype
is that all instances will share the same getCoffeeType
function instead of having a separate function (which does the same thing) on each instance. (see Use of 'prototype' vs. 'this' in JavaScript?). If you're running a large coffee chain and producing millions of coffees, then you'll probably save a fair amount of resources (i.e. memory).