Berrigan
Berrigan

Reputation: 438

ECMAScript2015 class vs Object.create vs new vs Object.setPrototypeOf

With the appearance of ES6 we got a new way of creating objects. My question is how should we create objects now? Let's say that the new operator works like this

function createNewObject(parentFunction){
    var obj = {};
    Object.setPrototypeOf(obj, parentFunction.prototype);
    return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}

But what exactly is happening when class is created? And what is the current "proper" way of creating objects in es6?

Upvotes: 3

Views: 2278

Answers (1)

Jackson
Jackson

Reputation: 3518

With es6 we would create a class using the following syntax:

class Animal{
    constructor(name){
        this.name = name;
    } 
    saySomething(){
        console.log('Hi, my name is' + this.name);
    }
}

If we want to create a sub class called Cat, it would look like this:

class Cat extends Animal {
    constructor(name){
        super(name);
    }   
    saySomething(){
        console.log('Meow, my name is ' + this.name);
    }
}

If we want to create an object of type Cat, we would do this:

let cat1 = new Cat('Felix');
cat1.saySomething(); //Outputs 'meow, my name is Felix'

The es6 class feature is syntactic sugar over the prototype method. If we were to create the Animal class using a regular prototype method it would look like this:

var Animal = function(name){
    this.name = name;
}
Animal.prototype.saySomething = function(){
   console.log('hi, my name is ' + this.name);
}

And the subclass would look like this:

var Cat = function(name){
    Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.saySomething = function(){
  console.log('Meow, my name is ' + this.name);
}

Upvotes: 5

Related Questions