ashwinik001
ashwinik001

Reputation: 5163

someFunction.Prototype.constructor vs someFunction.constructor

I am aware of the fact that functions in JavaScript lead a dual life first of a function (as first class thing to create instances from) and the second one of a normal object.

But I am surprised to see the output of the following console.

function A() {
    console.info("A");
}
console.info(A.prototype.constructor === A.constructor); // false

I expected it to be true as I was not expecting constructor property on the object A as it's own property. And hence following the prototypical chain lookup it should have been the same object as A.prototype.constructor. Where am I wrong or what piece am I missing?

Upvotes: 1

Views: 54

Answers (2)

Bergi
Bergi

Reputation: 664548

Where am I wrong or what piece am I missing?

That A does not inherit from A.prototype. A is a (constructor) function, and inherits from Function.prototype. Do a console.log(Object.getPrototypeOf(A)) :-)

From A.prototype only new A instances do inherit (whose .constructor is A). See also __proto__ VS. prototype in JavaScript.

Upvotes: 5

sachin.ph
sachin.ph

Reputation: 1078

That is beacuse both are returning different values.

  • Object.prototype.constructor

    Returns a reference to the Object function that created the instance's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

  • Function constructor

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

Also if you console above code you will see

console.info(A.prototype.constructor); outputs

function A() {
    console.info("A");
}

console.info(A.constructor); outputs

function Function() { [native code] } // both are different.

Upvotes: 1

Related Questions