Skip to content

Instantly share code, notes, and snippets.

@MartaJank
Forked from ross-u/ES5.js
Created November 17, 2020 15:21
Show Gist options
  • Save MartaJank/a741dc8aa1afdc0ab1e2f97062cd7c64 to your computer and use it in GitHub Desktop.
Save MartaJank/a741dc8aa1afdc0ab1e2f97062cd7c64 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
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 function constructors.
// This is done automatically by using the keyword `extends`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment