Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Uncaught ReferenceError: this is not defined" in class constructor

I am playing with the new stuff in JavaScript/ES6. I get an Uncaught ReferenceError: this is not defined(...) player.js:5 in my code. As far as I see, there are no errors here! Is this a bug? Any workarounds?

index.html

<html>     <head>         <script type="text/javascript" src="js/entity.js"></script>         <script type="text/javascript" src="js/player.js"></script>         <link href="css/style.css" rel="stylesheet" type="text/css">         <title>Test</title>     </head>     <body>         <canvas id="screen" width=500 height=500></canvas>         <script type="text/javascript">initialize();</script>     </body> </html> 

entity.js

"use strict";  class Entity {     constructor() {         console.log("Entity");     } } 

player.js

"use strict";  class Player extends Entity {     constructor() {         console.log("Created"); // <- error here     } } 
like image 920
bshaw Avatar asked Sep 11 '15 05:09

bshaw


People also ask

How do I fix uncaught ReferenceError is not defined?

Answer: Execute Code after jQuery Library has Loaded The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.

What does uncaught ReferenceError is not defined mean?

If you are using jQuery, Angular JS, or plain old JavaScript and getting "Uncaught ReferenceError: $ is not defined" error which means $ is either a variable or a method that you are trying to use before declaring it using the var keyword.


1 Answers

This is a fact of the new class syntax. Your subclass needs to call super() in order for the class to be properly initialized, e.g.

super(arg1, arg2, argN); 

with whatever arguments the parent constructor needs.

It is required that, if execution reaches the end of a constructor function, the value of this needs to have been initialized to something. You either need to be in a base class (where this is auto-initialized), have called super() so this is initialized, or returned an alternative object.

class Player extends Entity {   constructor() {     super();     console.log("Created"); ;// error here   } } 

You can think of it like constructor functions kind of have an automatic return this at the end of them.

like image 189
loganfsmyth Avatar answered Sep 28 '22 13:09

loganfsmyth