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
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.
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
)
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);
You can pass strings to new Function
to create functions out of them.
person1.constructor.constructor("console.log(1)");
is just like
Function("console.log(1)");
which returns a function that, when called, logs 1.
const fn = Function("console.log(1)"); console.log(fn); fn();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.