DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 57

The task is to implement Object.create()

The boilerplate code

function myObjectCreate(proto) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If the prototype is null or not an object, throw an error

if(proto === null || typeof !== "object") {
 throw new TypeError("Prototype must be an object or null")
}
Enter fullscreen mode Exit fullscreen mode

An empty constructor function is declared, because every object in Javascript is created using a constructor.

function F() {}
Enter fullscreen mode Exit fullscreen mode

The prototype of the empty constructor is set to the one provided

F.prototype = proto
Enter fullscreen mode Exit fullscreen mode

Then, a new instance is returned

return new F()
Enter fullscreen mode Exit fullscreen mode

The final code

function myObjectCreate(proto) {
  // your code here
  if(proto === null || typeof proto !== "object") {
    throw new TypeError("Prototype must be object or null")
  }

  function F() {}
  F.prototype = proto;
  return new F;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)