A quick but hard-to-google question:
var child = Object.create(parent.prototype);
var child = Object(parent.prototype);
Are they identical?
edit:
My question was raised by this two examples of inheritPrototype functions used to implement the Parasitic Combination Inheritance Pattern.
function inheritPrototype(childObject, parentObject) {
var copyOfParent = Object.create(parentObject.prototype);
copyOfParent.constructor = childObject;
childObject.prototype = copyOfParent;
}
http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
function inheritPrototype(subType, superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
"Parasitic Combination Inheritance" in Professional JavaScript for Web Developers
No they are not identical see below:
Object.create(prototype) will create a new prototype which inherits from the prototype passed as argument
Object(obj) or new Object(obj) will create a new instance of obj calling the constructor as well.
Now since prototypes are javascript objects as well, the difference can be minimal. However Object.create can handle constructors which may need arguments, while new Object() will not
Further info in this SO related answer (e.g differential inheritance, custom properties and so on)
References:
Object.create on MDNnew Object on MDNUPDATE after OP edit
In my OOP javascript framework Classy.js there is this polyfill around Object.create for older browsers which might shed light on your further question between differences:
Create = Obj.create || function( proto, properties ) {
var Type = function () {}, TypeObject;
Type[PROTO] = proto;
TypeObject = new Type( );
TypeObject[__PROTO__] = proto;
if ( 'object' === typeOf(properties) ) defineProperties(TypeObject, properties);
return TypeObject;
}
This polyfill can handle arbitrary constructors (with arguments) like Object.create can, and also make sure that the __proto__ is assigned correctly. The pattern using Object(prototype) in question is an attempt to (weakly-)reference the prototype.
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