首页 > 解决方案 > 什么是 instance.constructor.constructor 以及它是如何工作的?

问题描述

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.constructor吗?我不明白输出。person1.constructor.constructor("console.log(1)")person1.constructor.constructor("console.log(1)")()

标签: javascriptconstructor

解决方案


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

是什么Person?这是一个功能。函数的.constructor将是与该函数的内部原型关联的函数——即与 关联的构造函数,Function.prototypeFunction函数构造函数:

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)");

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

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


推荐阅读