Reputation: 21
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']);
Upvotes: 2
Views: 566
Reputation: 3214
At least in Chrome Object.create
is already defined as a function, so none of the code in the if
statement of the first example is being run. Without the if
statement, the code throwing the exception is run. The reason for the error is that the lambda function assigned to F
is not considered a constructor. Based on this answer, the problem is that the this
object is assigned to the scope surrounding a lambda function when it is created, while this
is assigned to the object calling the function when using a regular function. You can change the code to use a regular function instead:
let stooge = {
'first-name': 'John',
'last-name': 'Peter'
};
Object.create = (o) => {
let F = function() {};
F.prototype = o;
return new F();
};
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);
Upvotes: 1