...does the Prototype function have any purpose other than to achieve a mechanism of inheritance?
I assume you mean the prototype
property of Function
objects. (There is no "Prototype function" in JavaScript.)
It depends on what you mean by "inheritance." The purpose of the prototype
property on Function
instances is to specify the object that will be assigned as the prototype of objects created using that function as a constructor, e.g.:
var f = new Foo(); // Assigns `Foo.prototype` as `f`'s prototype
That way, f
has access to the properties defined by that prototype. If that's what you mean by inheritance, then yes, that's the only purpose for the prototype
property on functions.
Note that now we have ECMAScript5, you can assign prototypes without using constructor functions, if you prefer, using the new Object.create
:
var f = Object.create(somePrototype); // Assigns `somePrototype` as `f`'s prototype
Here's a more concrete example of both of those:
Using a constructor function:
function Foo(name) {
this.name = name;
}
Foo.prototype.hey = function() {
console.log("Hi, I'm " + this.name);
};
var f = new Foo("Fred"); // Assigns `Foo.prototype` as `f`'s prototype
f.hey(); // Shows "Hi, I'm Fred" because `f` gets `hey` from its prototype
Using Object.create
:
var fproto = {
hey: function() {
console.log("Hi, I'm " + this.name);
}
};
var f = Object.create(fproto); // Assigns `fproto` as `f`'s prototype
f.name = "Fred";
f.hey(); // Shows "Hi, I'm Fred" because `f` gets `hey` from its prototype
So if you prefer only to use Object.create
, and you're only using ES5-enabled engines, you could never use Function#prototype
at all if you like.