Your problem is that you're defining the Foo.prototype object, and as such, you're bound to the rules and syntax of object creation, for example the parser expects you to list the attributes in a key: value, nextkey: nextvalue
format, which Bar.prototype does not fit. (Keys are effectively strings, and it doesn't make sense to use .
in them, as they would create ambiguity while parsing*)
Try this:
var Foo = function Foo() {};
Foo.prototype.Bar = function Bar() { };
Foo.prototype.Bar.prototype = {
barMethod: function () {
console.log('hello');
}
};
There's a slight semantic difference though, as this way you're not overriding the prototype, just extending it. (consider equaling it to {}
first, then extending it with every attribute of the object you tried to create)
(*) A note on ambiguity: I mention above that having a .
in your object key would create ambiguity, here's a simple example:
var foo = {
bar: {
baz: 0,
qux: 20
},
bar.baz: 150 //note that this will throw an error
};
console.log(foo.bar.baz);
If this code above wouldn't throw an error, what would you expect console.log(foo.bar.baz)
to print, 0 or 150?
That's why it doesn't make sense to use .
in a key, and that's why the parser throws the unexpected token error on any .
.
Of course, you could use the "bar.baz" string as a key as "bar.baz": 150
above (please don't!), but then you'd have to reference the value as
foo["bar.baz"]
which would be distinctly different from
foo.bar.baz;
All in all, this is just some intuition-based reasoning behind why you can't use a .
in your keys, but the real reason is plainly this: because the parser will throw an error.