AI solution for JavaScript Coding Question on BFE.dev
60. create your own `new` operator
Here is a possible implementation of myNew()
function:
function myNew(constructorFn, ...args) { const instanceObj = Object.create(constructorFn.prototype); const result = constructorFn.apply(instanceObj, args); return (typeof result === "object" && result !== null) ? result : instanceObj;}
In this implementation, we first create an empty object that has constructorFn.prototype
as its prototype, using Object.create()
. This will make the new object inherit from the prototype object of the constructor function.
Then, we call the constructorFn
function with the new object as its context (this
), using apply()
. This will execute the constructor function in the context of the new object, so that any properties that the constructor assigns to this
will be added to the new object.
Finally, we check if the constructor function returns an object (which would be the case if the constructor is meant to return a different type of object than the one being instantiated), and return that object if it does. If not, we return the new object that we created.
Note that this implementation assumes that the constructorFn
function does not use the new.target
keyword inside it to check if it was called with new
or not. Otherwise, we would need to find a different way to emulate the behavior of new
.