The task is to implement myNew function to return an object just like the new constructor.
const myNew = (constructor, ...args) => {
// your code here
}
How does the new operator work? It creates a new empty object, sets the prototype of that object to the constructor's prototype, calls the constructor function, and returns the object the constructor returns or the newly created one.
If the constructor is not a function, throw an error
if (typeof constructor !== 'function') {
throw new TypeError('myNew: first argument must be a constructor function');
}
Create the new object to be returned if the constructor does not return one
const obj = Object.create(constructor.prototype);
Call the constructor with "this" set to the new object
const result = constructor.apply(obj, args);
If the constructor returns an object (or function), return it. Otherwise, return the new function
return (result !== null && (typeof result === 'object' || typeof result === 'function'))
? result
: obj;
The final code
const myNew = (constructor, ...args) => {
// your code here
if(typeof constructor !== 'function') {
throw new TypeError('myNew: first argumant must be a function')
}
const obj = Object.create(constructor.prototype);
const result = constructor.apply(obj, args)
return (result !== null && (typeof result === 'object' || typeof result === 'function'))
? result : obj;
}
That's all folks!
Top comments (0)