繁体   English   中英

什么是 instance.constructor.constructor 以及它是如何工作的?

[英]What is instance.constructor.constructor and how does it work?

function Person(name) {
    this.name = name;
}   

let person1 = new Person("Eve");

person1.constructor; // Output: ƒ Person(name) {}

person1.constructor.constructor; // Output: ƒ Function() { [native code] }

person1.constructor.constructor("console.log(1)"); // Output: ƒ anonymous() {console.log(1)}

person1.constructor.constructor("console.log(1)")(); // Output: 1

有人可以帮我理解person1.constructor.constructorperson1.constructor.constructor("console.log(1)")person1.constructor.constructor("console.log(1)")()吗? 我不明白输出。

实例的.constructor属性指向与内部原型关联的 function。 如您所见, person1.constructor为您提供Person ,因为person1是使用new Person创建的( person1的内部原型是Person.prototype

什么是Person 这是一个 function。 The .constructor of a function will be the function associated with the internal prototype of that function - that is, the constructor associated with Function.prototype , which is Function , the function constructor:

 function Person(name) { this.name = name; } let person1 = new Person("Eve"); console.log(person1.constructor.constructor === Function);

您可以将字符串传递给new Function以从中创建函数。

person1.constructor.constructor("console.log(1)");

就像

Function("console.log(1)");

它返回一个 function ,调用时记录 1。

 const fn = Function("console.log(1)"); console.log(fn); fn();

暂无
暂无

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

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