'Why does a class have a "constructor" field in JavaScript?

A class is supposed to have a prototype field that supplies default fields. For example, prototype.constructor defaults to the constructor function (i.e., the class itself) and is therefore accessible as the constructor field in new objects:

function MyClass(){}
console.log(MyClass.prototype.constructor === MyClass); // true
console.log(new MyClass().constructor === MyClass); // true

That's all fine and good. However, if we accidently confuse the class and the object, we would expect an error, since the class shouldn't have a constructor field. But it does:

console.log("constructor" in MyClass);        // true
console.log(MyClass.constructor === MyClass); // false

Why does the class itself have a constructor field, and why is it not the same as protoype.constructor? Wouldn't this lead to lots of bugs, since a program could inadvertently access the constructor field of a class?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source