Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active January 18, 2021 16:20
Show Gist options
  • Save ross-u/3fcddfaf3ba7196e2158c097c74c8a6b to your computer and use it in GitHub Desktop.
Save ross-u/3fcddfaf3ba7196e2158c097c74c8a6b to your computer and use it in GitHub Desktop.
JS | Prototypes - ES5 vs ES6 syntax

JS | Prototypes - ES5 vs ES6 syntax


Examples for the parallel comparison of the ES5 and ES6 syntaxes, used for creating object constructors in JS.


function Product(name, price) {
this.name = name;
this.price = price;
}
Product.prototype.nameAndPrice = function() {
console.log(
"The product's name is: " + this.name,
"and the product's price is: " + this.price,
);
};
// Extend Product to Toy
function Toy(name, price, brand) {
Product.call(this, name, price);
this.brand = brand;
}
// Extend the prototype
// Object.create() is used to connect the `Toy.prototype.__proto__` to `Product.prototype`
// When using class the same thing is done automatically when using keyword `extends`
Toy.prototype = Object.create(Product.prototype);
Toy.prototype.constructor = Toy;
// The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
nameAndPrice() {
console.log(
"The product's name is: " + this.name,
"and the product's price is: " + this.price,
);
}
}
class Toy extends Product {
constructor(name, price, brand) {
super(name, price); // `super` is equivalent to: `Product.call(this, name, price)`
this.brand = brand;
}
}
// We don't have to explicitly "extend the prototype" like with the ES5 function constructors.
// This is done automatically by JS when using the keyword `extends`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment