Skip to content

Instantly share code, notes, and snippets.

@newbornfrontender
Created January 18, 2019 07:15
Show Gist options
  • Save newbornfrontender/02ee8ba9e2770811dc6e76566981870a to your computer and use it in GitHub Desktop.
Save newbornfrontender/02ee8ba9e2770811dc6e76566981870a to your computer and use it in GitHub Desktop.
Objects, Prototypes and Classes in JavaScript
// -----------------------------------------------------------------------------
// Objects
// -----------------------------------------------------------------------------
// const Reptile = function(name, canItSwim) {
// this.name = name;
// this.canItSwim = canItSwim;
// };
// Reptile.prototype.doesItDrown = function() {
// if (this.canItSwim) console.log(`${this.name} can swim`);
// else console.log(`${this.name} has drowned`);
// };
// const alligator = new Reptile('alligator', true);
// const croc = new Reptile('croc', false);
// alligator.doesItDrown();
// croc.doesItDrown();
// -----------------------------------------------------------------------------
// Prototypes
// -----------------------------------------------------------------------------
// croc.__proto__.doesItDrown = function() {
// console.log(`the croc never drowns`);
// };
// alligator.doesItDrown();
// croc.doesItDrown();
// -----------------------------------------------------------------------------
// Classes
// -----------------------------------------------------------------------------
class Reptile {
constructor(name, canItSwim) {
this.name = name;
this.canItSwim = canItSwim;
};
doesItDrown() {
if (this.canItSwim) console.log(`${this.name} can swim`);
else console.log(`${this.name} has drowned`);
};
};
const alligator = new Reptile('alligator', true);
const croc = new Reptile('croc', false);
alligator.doesItDrown();
croc.doesItDrown();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment