Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Prototypal instantiation vs Pseudoclassical instantiation

I read through several other articles on prototypal vs pseudoclassical instantiation and still have a few questions. I have included code below for illustration.

Questions are:

  1. Is Person effectively the same as Human?
  2. Are John and Alice essentially the same?
  3. What side effects can result from one way vs the other?
  4. Are there any significant performance issues I should be aware of?

    var Person = function() {
     hopes: function(){},
     dreams: function(){}
    };
    
    var John = Object.create(Person); // not supported in older browsers
    

    --

    var Human = function() {
    };
    
    Human.prototype.hopes = function(){}; // could add both hopes & dreams with an object
    Human.prototype.dreams = function(){};
    
    var Alice = new Human();
    
like image 759
arami Avatar asked May 07 '26 09:05

arami


1 Answers

Your syntax is a bit off in the first example, but yes, these will result in objects that are similar. In the first example, it should be:

var Person = {
 hopes: function(){},
 dreams: function(){}
};

There are some subtle differences though. Using the new keyword causes an object to be added to the prototype chain, e.g. Alice will now use Human's prototype chain. Object.create sets the object's prototype to the parameter, e.g. Person is John's prototype. These generally will be similar, except if you do Object.create(null), in which case you don't get the basic object prototype as if you did new Object();

You can run performance tests here http://jsperf.com/obj-create-vs-new/4

like image 191
Jeff Storey Avatar answered May 08 '26 21:05

Jeff Storey