首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是instance.constructor.constructor ?它是如何工作的?

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

Stack Overflow用户
提问于 2021-01-26 11:26:51
回答 1查看 38关注 0票数 0
代码语言:javascript
复制
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)")()吗?我不理解输出结果。

EN

回答 1

Stack Overflow用户

发布于 2021-01-26 11:31:58

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

什么是Person?它是一个函数。函数的.constructor将是与该函数的内部原型关联的函数-即与Function.prototype关联的构造函数,即函数构造函数Function

代码语言:javascript
复制
function Person(name) {
    this.name = name;
}   

let person1 = new Person("Eve");

console.log(person1.constructor.constructor === Function);

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

代码语言:javascript
复制
person1.constructor.constructor("console.log(1)");

就像

代码语言:javascript
复制
Function("console.log(1)");

它返回一个函数,该函数在被调用时记录为1。

代码语言:javascript
复制
const fn = Function("console.log(1)");
console.log(fn);
fn();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65895494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档