I'm trying to understand how object prototypes work and hence tried out a piece of code from 'Javascript: The Good Parts' book and got an error.
I modified the code just for fun and got the error. It works and shows an output if the original code is ran.
This is the original code and it gave no errors.
let stooge = {
'first-name': 'John',
'last-name' : 'Peter'
};
if(typeof Object.create !== 'function') {
Object.create = (o) => {
let F = () => {};
F.prototype = o;
return new F();
};
}
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);
I removed the if condition and got an error saying F isn't a constructor function. Could someone explain me why this is happening? Please excuse me, I'm a beginner to programming.
Modified code:
let stooge = {
'first-name': 'John',
'last-name' : 'Peter'
};
Object.create = (o) => {
let F = () => {};
F.prototype = o;
return new F();
};
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);