Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Object.create(prototype) and Object(prototype)

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

like image 887
hwechselberg Avatar asked Dec 01 '25 06:12

hwechselberg


1 Answers

No they are not identical see below:

  1. Object.create(prototype) will create a new prototype which inherits from the prototype passed as argument

  2. 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:

  1. Object.create on MDN
  2. new Object on MDN

UPDATE 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.

like image 185
Nikos M. Avatar answered Dec 03 '25 18:12

Nikos M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!