问题描述
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)")()
?我不明白这些输出.
Can someone help me to understand person1.constructor.constructor
, person1.constructor.constructor("console.log(1)")
and person1.constructor.constructor("console.log(1)")()
? I do not understand the outputs.
推荐答案
实例的 .constructor
属性指向与内部原型关联的函数.如您所见, person1.constructor
为您提供 Person
,因为 person1
是用 new Person
( person1
的内部原型是 Person.prototype
)
The .constructor
property of an instance points to the function associated with the internal prototype. As you can see, person1.constructor
gives you Person
, because person1
was created with new Person
(person1
's internal prototype is Person.prototype
)
什么是 Person
?这是一个功能.函数的 .constructor
将是与该函数的内部原型相关联的函数-即与 Function.prototype
相关联的构造函数,即 Function
,函数构造函数:
What is the Person
? It's a 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
以从中创建函数.
You can pass strings to new Function
to create functions out of them.
person1.constructor.constructor("console.log(1)");
就像
Function("console.log(1)");
返回一个函数,该函数在调用时将记录为1.
which returns a function that, when called, logs 1.
const fn = Function("console.log(1)");
console.log(fn);
fn();
这篇关于什么是instance.constructor.constructor,它如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!