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)")()吗?我不理解输出结果。
发布于 2021-01-26 11:31:58
实例的.constructor属性指向与内部原型关联的函数。正如您所看到的,person1.constructor提供了Person,因为person1是用new Person创建的(person1的内部原型是Person.prototype)
什么是Person?它是一个函数。函数的.constructor将是与该函数的内部原型关联的函数-即与Function.prototype关联的构造函数,即函数构造函数Function:
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();
https://stackoverflow.com/questions/65895494
复制相似问题