What is o ?
If I am not mistaken, prototype means that F is going to inherit from o , but that is all I can understand here.
Can someone break this down for me:
if (!Object.create) {
Object.create = (function () {
var F = function(){};
return function (o) {
if (arguments.length !== 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
}());
o is a parameter that you pass into the function.
For example:
var myObj = Object.create({
myFn: function(){}
});
Then you can do:
myObj.myFn();
The context of that code can help you understand it better.
This polyfill covers the main use case which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
The code is intended to serve as a replacement for Object.create(proto [, propertiesObject ]) when Object.create is not provided by the environment.
So, o is just the object which will serve as the prototype of the new object you are creating.
In practice, this means that we can use o as our superclass (or more correctly o is the prototype of our superclass).
The example from the Mozilla docs makes this clear:
//subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Answering the comment, this feels a little too long for the comment box:
o is the prototype of the object you want to inherit from. Technically it is an object too, everything in JS is an object. How is almost everything in Javascript an object?.
Why would you want to inherit from another object? What's the point of OOP?
What does this line do? F.prototype = o;
Lets repeat the full code, except with comments:
// if the execution environment doesn't have object.create, e.g. in old IE
if (!Object.create) {
// make object.create equal to something
Object.create = (function(){
// create a new object F which can be inherited from
function F(){}
// return a function which
return function(o){
// throw an error if
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
// force F to inherit o's methods and attributes
F.prototype = o
// return an instance of F
return new F()
}
})() // this is an IIFE, so the code within is automatically executed and returned to Object.create
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With