Kyoma
Kyoma

Reputation: 209

What is instance.constructor.constructor and how does it work?

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.

Upvotes: 0

Views: 170

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

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();

Upvotes: 1

Related Questions