0

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?

7
  • 2
    MyClass it itself an object: It's a Function object. MyClass.constructor is therefore the Function constructor! console.log(MyClass.constructor == Function.prototype.constructor) /* true */ Commented May 13, 2022 at 20:01
  • 1
    using in operator you check not only the object but also their prototype... Commented May 13, 2022 at 20:08
  • I'm confused about your confusion. A class has a constructor. Once constructed, the object "is a" class instance and therefore has a constructor too. If you want to construct another object from the object reference, you can just do var newInstance = new myObject.constructor();. Obviously you could use Object.create too, but whateverr. Not sure there's much risk of programs "accidentally" accessing a constructor property any more than "accidentally" accessing its __proto__ property... Commented May 13, 2022 at 20:11
  • @Heretic The question is why does a class have a constructor. The class wasn't constructed by a function. It was constructed by a function definition statement. Commented May 13, 2022 at 20:20
  • 1
    For any object, object.constructor is the constructor for creating another instance of that object. Classes are objects too. They are Function objects. So MyClass.constructor is the constructor for creating another Function object. MyClass.constructor("blah") is just a confusing way of writing new Function("blah"). Commented May 13, 2022 at 20:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.