0

As I understand the .constructor value is a Function() for classes.

In short, why constructor attribute is a Function and whta the rational about it?

Example: Set.constructor -> Function()

0

1 Answer 1

1

Classes are (very) special kinds of functions; Set inherits from Function.prototype.

Function.prototype has a constructor property - that's what Set.constructor refers to. (Set does not have an own constructor property - it's only inherited.)

The constructor of Function.prototype is what you can call to create a Function instance - which, in this special case, is just Function.

console.log(Set.constructor === Function);

So

Set.constructor('alert(1);')

is equivalent to

Function('alert(1);')
Sign up to request clarification or add additional context in comments.

2 Comments

I was initially confused by this, but now it’s very obvious to me. I’ll provide an alternative way of explaining this: The thing that creates new Set objects sits at Set.prototype.constructor which of course is just Set itself. Set.prototype is the object that hosts all the methods and properties that all Set objects have in common and the constructor property within it just points back to Set itself. (1 / 2)
(2 / 2) Set.constructor, however would be a static property of Set. Since this would just be an arbitrary property with no special meaning, it doesn’t exist, at least not as an own property; but it is inherited! It’s inherited from some kind of object with methods and properties that all functions (which classes are a “(very) special” kind of) have in common. Well, that object would be Function.prototype, of course! And yes, that’s Function.prototype.constructor, indeed, which, by the same reasoning as with Set.prototype.constructor, is Function.

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.