Reputation: 2310
I'm using Require.js and CoffeeScript. I have what I find to be a rather strange error.
I have the following definition:
define ->
{
Node: class
ChildNode: class extends @Node
Term: class
ChildTerm: class extends @Term
}
This raises the following error:
Uncaught TypeError: Cannot read property 'prototype' of undefined
However, the following both work fine:
define ->
{
Node: class
ChildNode: class extends @Node
}
define ->
{
Node: class
ChildNode: class extends @Node
Term: class
ChildTerm: class extends @Node
}
What is wrong with my code such that I can't extend Term
? I can't see anything different between it and Node
.
Upvotes: 0
Views: 2905
Reputation: 664599
However, the following both work fine
Actually they don't. Have a look at what code they're producing:
// [simplified, obviously]
function __extends(child, parent) {
child.prototype = Object.create(parent.prototype);
return child; // ^^^^^^^^^^^^^^^^
}
define(function() {
return {
Node: function _Class() {},
ChildNode: __extends(function _Class() {}, this.Node)
} // ^^^^^^^^^
})
You cannot have Self-references in object literal declarations.
So why does subclassing
Term
like this throw an error while withNode
it does not?
Because the this
does refer to the global object. And that does actually have a Node
property already: the DOM Node
interface constructor (which you cannot subclass, though). With Term
however, you are passing undefined
to __extend()
.
Upvotes: 3