简体   繁体   中英

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM