AI solution for JavaScript Coding Question on BFE.dev
94. implement your own `Object.create`
Here's one possible solution to implement myObjectCreate()
:
function myObjectCreate(proto) { if (typeof proto !== 'object' || proto === null) { throw new Error('Object prototype may only be an Object or null'); } function F() {} F.prototype = proto; return new F();}
This function takes a proto
parameter and creates a new object with proto
as its prototype.
The function first checks that the proto
parameter is indeed an object (including Array
and null
) and throws an error if it is not. This is to avoid any potential issues related to setting the prototype to null.
Then the function creates an empty constructor function F()
that acts as a surrogate empty object. The F.prototype
property is set to proto
, effectively inheriting from it. Finally, the function returns a new instance of F()
, which is empty but inherits from proto
.
This implementation is not exactly the same as Object.create()
, since it does not support the optional propertiesObject
argument. However, it should work for basic usage of prototype inheritance.