简体   繁体   English

someFunction.Prototype.constructor与someFunction.constructor

[英]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. 我知道以下事实:JavaScript中的函数导致函数的双重生命(作为创建实例的第一类东西)和普通对象的第二生命。

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. 我期望它是真实的,因为我不期望对象A constructor属性是它自己的属性。 And hence following the prototypical chain lookup it should have been the same object as A.prototype.constructor . 因此, A.prototype.constructor原型链查找之后,它应该与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不继承自A.prototype A is a (constructor) function, and inherits from Function.prototype . A是(构造函数)函数,并且继承自Function.prototype Do a console.log(Object.getPrototypeOf(A)) :-) 做一个console.log(Object.getPrototypeOf(A)) :-)

From A.prototype only new A instances do inherit (whose .constructor is A ). A.prototype仅继承new A实例(其.constructorA )。 See also __proto__ VS. 另请参见__proto__VS。 prototype in JavaScript . JavaScript中的原型

That is beacuse both are returning different values. 那是因为两者都返回不同的值。

The Function constructor creates a new Function object. Function构造函数创建一个新的Function对象。 In JavaScript every function is actually a Function object. 在JavaScript中,每个函数实际上都是一个Function对象。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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