RSS DEV Community

Coding Challenge Practice - Question 45

The `myNew` function aims to replicate the behavior of the `new` operator in JavaScript. It accepts a `constructor` function and any subsequent `args` to pass to it. First, it validates that the `constructor` argument is indeed a function, throwing a TypeError if it's not. It then creates a new empty object using `Object.create`, setting its prototype to the `constructor`'s prototype. This ensures the new object inherits properties from the constructor's prototype. The `constructor` function is then called using `apply`, with its `this` keyword bound to the newly created object and the provided arguments. The result of this constructor call is stored. Finally, the function checks if the `constructor` returned a non-null object or function. If it did, that returned value is returned; otherwise, the newly created object `obj` is returned. This entire process mimics how the native `new` operator instantiates objects.
favicon
dev.to
dev.to
Create attached notes ...