Much like a class Foo
is not itself the same type as a new Foo
, there is no reason for Foo
to have any properties you assign to Foo.prototype
. The reasons are a little different, but consider it in another language like java and it's apparent that what you're trying to do just should not work:
class Foo {
public String bar = "analogous to Foo.prototype.bar which is a property of Foo instances";
}
class Baz {
String thisMethodShouldAndWillFail() {
return Foo.bar;
}
String thisIsWhatShouldAndWillWork() {
return (new Foo()).bar;
}
}
In javascript, you need to correct your idea of what a prototype is and how it is related to objects and constructors, or you will run into problems continually. A foo
has a prototype, but that prototype is not foo.prototype
. There is no property of foo
itself that is its prototype. The foo
's prototype is determined by its constructor Foo
; it makes more sense this way because you could assign any old value to foo.prototype
after it is constructed, which breaks foo
by turning it into an instance of a class for which it was not initialized.
The constructor Foo
would similarly not make any sense if it would act as an instance of the class it defines; it has not been initalized by itself, so it cannot safely be assumed that it will fulfill the behavior intended for its instances. Foo
is an instance of Function
, which makes sense because it can be called. Therefore the prototype of Foo
is Function.prototype
, not Foo.prototype
.
The relationship between a foo
and its prototype is set up when you call foo = new Foo
. Since the body of the constructor Foo
is expected to initialize the instance, this is the only time to give foo
its prototype that makes sense. The prototype provides an object its common behaviors, the constructor initializes the object so that these behaviors will work as intended. The prototype that is assigned to foo
when it is constructed via new Foo
is none other than Foo.prototype
; this is done before Foo
is executed for convenience and a guarantee that it cannot possibly be messed up. Following that, there is no way to access the prototype of foo
without going through Foo
explicitly.
enter code here