For this task, I need to implement the Object.create polyfill.
Object.create - Creates and returns a new object whose prototype is the first argument passed to the function. If a second argument is passed, sets it as properties for the new object.
The function must take two parameters:
prototype (required) - An object, or null (but not undefined), which will be the prototype for the created object.
properties (optional) - an argument that will set properties for the new object (will be passed to Object.defineProperties).
If there are no function parameters or prototype is NOT an object or null, then a TypeError must be thrown.
As a result, Object.create will return the created object with the [[Prototype]] internal property set to the value passed in the prototype argument. If properties are passed and is NOT undefined, then Object.defineProperties (obj, properties) will be called, where obj is the object to be returned from Object.create.
Example:
const A = {
objectName: 'Object A',
getObjectName: function() {
return `This is ${this.objectName}!`;
},
};
const B = Object.create(A, {
objectName: {
value: 'Object B',
},
});
A.getObjectName(); // This is Object A!
B.getObjectName(); // This is Object B!
A.hasOwnProperty('getObjectName'); // true
A.hasOwnProperty('objectName'); // true
B.hasOwnProperty('getObjectName'); // false
B.hasOwnProperty('objectName'); // true
The solution to the task must be written in this function:
Object.create = function(proto, propertiesObject) {
//code here
}
My try:
Object.create = function(proto, propertiesObject) {
if (typeof proto !== 'object' && typeof proto !== 'function') {
throw new TypeError();
} else if (proto === null) {
return {};
}
if (typeof propertiesObject != 'undefined') return
function F() {}
F.prototype = proto;
return new F();
};
Only 2 points fail on the test (where there are crosses):
✕ must return an empty object when called with a null argument (10ms)
✓ `prototype` argument works as expected (1ms)
✕ the `properties` argument works as expected (1ms)
✓ object A must be the prototype of object B (1ms)
✓ objects A and B must be different (1ms)
✓ without arguments there must be a TypeError (2ms)
✓ if the first parameter is not an object or null then there must be a TypeError (2ms)
Help me please do it right