javascript - 什么是 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)")()
解决方案
实例的.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();
推荐阅读
- ios - swift: ContainerView 正确动作
- ios - Obj-C,CLS_LOG Crashlytics 日志记录未在 Xcode 控制台中显示调试输出?
- node.js - NodeJS - 如何从承诺中获取数据返回并将其导出
- javascript - 在事件监听器中使用 typeof
- swift - Swift:UIImageView 的 CropView
- mysql - 从 sql 过滤
- java - oracle 带 JDBC 删除账户功能
- windows - C++ 将 32 位 bmp 图像转换为 24 位 bmp 和 16 位 bmp
- html - 嵌入 html 图片 tkinter
- c++ - QWidget中的QLayout