Object.create vs the new operator in Javascript

One of the more advanced topics in Javascript is the distinction between the Object.create() and the new operator when constructing new objects. More than that, Javascript being a client side language – is unlike other server side languages, compiled or interpreted.

As a result Javascript has some weird parts to it putting off some developers to some other more less dynamics languages but drawing in more curious developers to Javascript land. These weird parts shouldn’t be seen as a disadvantage though if you thoroughly spend quality time getting to know Javascript – you can use these new patterns, concepts to your advantage.

I say this is an advanced topic because only a seasoned, experienced developer would have seen the changes Javascript has undergone within the past two decades. First, Javascript was originally created to draw in Java developers of the time. However, Javascript is unlike Java or any other language for that matter.

On this post I am going to cover the subject of “Inheritance” in that Javascript differs from the “Classical Approach”. In the “Classical Approach” I am going to use PHP to illustrate a common convention or pattern. Then, in contrast, provide an example of how Javascript provides this feature.

In OOP (Object Oriented PHP), a class is created and then from that defined class, other objects can extend from it.


//The parent class
class Car {

  // Private property inside the class
  private $model;
 
  //Public setter method
  public function setModel($model)
  {
    $this -> model = $model;
  }
 
  public function hello()
  {
    return "beep! I am a <i>" . $this -> model . "</i><br />";
  }
}
 
//The child class inherits the code from the parent class
class SportsCar extends Car {
  //No code in the child class
}
 
//Create an instance from the child class
$sportsCar1 = new SportsCar();
  
// Set the value of the class’ property.
// For this aim, we use a method that we created in the parent
$sportsCar1 -> setModel('Mercedes Benz');
  
//Use another method that the child class inherited from the parent class
echo $sportsCar1 -> hello();

Here we see the SportCar class inheriting the setModel method from its parent class – the Car class. Pretty straightforward example.

However in Javascript – the idea of inheritance is better understood by a concept known as “prototypal inheritance”. When we dive underneath the hood, I find it really interesting on how Javascript does it.

Building Function Constructors


function Person(firstname, lastname) {

  console.log(this);
  this.firstname = firstname;
  this.lastname = lastname;
  console.log('This function is invoked');
}

// Attach a method to the Person Object
Person.prototype.getFullName = function() {
  return this.firstname + ' ' + this.lastname;
}

var john = new Person('John', 'Doe');
console.log(john);

var jane = new Person('Jane', 'Doe');
console.log(jane);

// will output:

/*
Person {}
This function is invoked
Person { firstname: 'John', lastname: 'Doe' }
Person {}
This function is invoked
Person { firstname: 'Jane', lastname: 'Doe' }
*/

The output here isn’t as important as understanding how prototypal inheritance works. With prototypal inheritance, we are attaching methods and properties to an objects ‘prototype’, something every object in Javascript comes built with. Let’s not forget – Everything in Javascript is an object.

In the previous example, notice we used the ‘new’ operator to create new objects.

Modern browsers however now support a simpler way, using the “Object.create()” method. As you will see in the example below a polyfill has been added to provide support for browsers that don’t support this method.


// implement polyfill
if (!Object.create) {

        Object.create = function(o) {
                if(arguments.length > 1) {
                        throw new Error('Object.create implementation' + ' only accepts the first parameter');
                }

        function F() {}
        F.prototype = o;
        return new F();

        }

}

var person = {
        firstname: 'Default',
        lastname: 'Default',
        greet: function() {
                return 'Hi ' + this.firstname;
        }
}

var john = Object.create(person);

john.firstname = 'John';
john.lastname = 'Doe';

john.greet();

console.log(john);

Unlike the ‘new’ operator, Object.create() looks like a simplified approach – and this is truly the case. It IS really that simple. The only difference here is that you can construct new objects from object literals! Pretty interesting.