Peter Seliger
1 min readFeb 1, 2024

--

Considering the article being the essence of a self learning project, following points are going to be criticized.

First of all, one never can pass a constructor function which was created by class syntax.

Second, the usage of __proto__ is highly discussable but a direct consequence of applying the constructor function like that ...

let result = Constructor.apply(newObj, args);

The latter has two disadvantages. Class constructors can not be invoked via call or apply. Doing so does throw a TypeError. And since the invocation via the latter two methods is totally agnostic to any involved prototypes, unlike with a real instantiation via a constructor function invoked with the new keyword, one of cause has to wire it up manually. But then, using Object.setPrototypeOf should have been the preferred way, thus ...

Object.setPrototypeOf(newObj, Constructor.prototype);

... instead of ...

newObj.__proto__ = Constructor.prototype;

For real world use cases where one is very deep within a system and relies on introspection and reflection, there is already a function-based variant as alternative to invoking a constructor function with new, it is Reflect.construct which does work with ES3 constructor functions and real class-constructors alike.

class Person {
constructor(name, age) {
Object.assign(this, { name, age });
}
showMyName() {
console.log(this.name);
}
}
const person = Reflect.construct(Person, ["Mrx", 12]);

person.showMyName();

console.log(
'(person instanceof Person) ?..',
(person instanceof Person),
);
console.log(
'person.constructor ...',
person.constructor,
);
console.log(
'Object.getPrototypeOf(person) ...',
Object.getPrototypeOf(person),
);

--

--

No responses yet