Examples for the parallel comparison of the ES5 and ES6 syntaxes, used for creating object constructors in JS.
-
-
Save MartaJank/a741dc8aa1afdc0ab1e2f97062cd7c64 to your computer and use it in GitHub Desktop.
JS | Prototypes - ES5 vs ES6 syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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