-3

Take a look at this JavaScript code. When running my webpage, it says:

TypeError: Dictionary is not a Constructor.

However, when I copy and paste the same thing at Firefox console, it works flawlessly. What's the matter with it?

Muntashir Akon
  • 8,740
  • 2
  • 27
  • 38
  • 1
    Please include the relevant code here... having looked though, it seems that it could be a bug in the Firefox console - it _shouldn't_ work there either (and actually doesn't work in my Firefox console - you must have not put it in exactly as you have it there). It doesn't work in the Chrome console for instance - same error. – James Thorpe Mar 31 '16 at 11:15
  • Try each objects separately. – Muntashir Akon Mar 31 '16 at 11:19
  • 1
    Possible duplicate of [Does a Javascript function have to be defined before calling it?](http://stackoverflow.com/questions/9973461/does-a-javascript-function-have-to-be-defined-before-calling-it) – James Thorpe Mar 31 '16 at 11:24
  • In short, `Dictionary` is defined (but with a value of `undefined`) as the definition is hoisted to the top, but the function isn't assigned until long after you've attempted to run `new Dictionary`. – James Thorpe Mar 31 '16 at 11:25
  • @JamesThorpe it seems to be a duplicate, but I didn't realize it until the answer was given. – Muntashir Akon Mar 31 '16 at 11:30

2 Answers2

2

Is it because hoisting?

var dict = new Dictionary();
var Dictionary = function () { ... };

is just like

var Dictionary;
var dict = new Dictionary();
Dictionary = function () { ... };

So when you new, variable Dictionary is undefined.

Yan Yang
  • 1,804
  • 2
  • 15
  • 37
1
var dict = new Dictionary() 

This part of the code must be placed AFTER the definition of Dictionary, otherwise it obviously fails. It works in your console because the console will run after the object has been defined, whereas in your code you are trying to instanciated a class that does not exist yet.

Mijamo
  • 3,436
  • 1
  • 21
  • 21