Last active
June 1, 2021 22:05
-
-
Save adamdoe/65b175aea77fc389017d7c4150513a72 to your computer and use it in GitHub Desktop.
Animal.js #js
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
/** | |
* ES6 Classes | |
* Notes: | |
* - instead of adding methods to the prototype | |
* can add them directly to class. | |
*/ | |
class Animal { | |
constructor(name, age) { | |
this._name = name; | |
this._age = age; | |
} | |
get name() { | |
return this._name; | |
} | |
get age() { | |
return this._age; | |
} | |
eat() { | |
} | |
sleep() { | |
} | |
} | |
// Extending classes | |
class Dog extends Animal { | |
constructor(name, age, breed) { | |
super(name,age); // equivalent to Animal.call(this, name, age); | |
this.breed = breed; | |
} | |
} | |
/** | |
* Constructor Function without prototype | |
* Notes: | |
* - inheriting methods from another object | |
* - Exclusion of new keyword | |
* */ | |
const animalMethods = { | |
eat(amount) { | |
console.log(`${this.name} is eating.`) | |
this.energy += amount; | |
} | |
play() { | |
console.log(`${this.name} is playing`) | |
} | |
} | |
function Animal(name, energy) { | |
let animal = Object.create(animalMethods); | |
animal.name = name; | |
animal.age = age; | |
animal.sleep = function(energy) { | |
console.log('sleeping') | |
} | |
return animal; | |
} | |
// notice the exclusion of new keyword. | |
const snoop = Animal('snoop', 7); | |
/** | |
* Constructor Function using prototype | |
* Notes: | |
* - Using prototype | |
* - Exclusion of new keyword | |
* */ | |
function Animal(name, energy) { | |
let animal = Object.create(Animal.prototype); | |
animal.name = name; | |
animal.energy = energy; | |
return animal; | |
} | |
Animal.prototype.eat = function(amount) { | |
console.log(`${this.name} is eating.`) | |
this.energy += amount; | |
} | |
// notice the exclusion of new keyword. | |
const snoop = Animal('snoop', 7); | |
/** | |
* Constructor Function using prototype and new keyword | |
* Notes: | |
* - Using prototype | |
* - new keyword | |
* */ | |
function AnimalWithNew(name, energy) { | |
// let this = Object.create(Animal.prototype); | |
this.name = name; | |
this.energy = energy; | |
// return this; | |
} | |
// notice the exclusion of new keyword. | |
const snoop = new Animal('snoop', 7); | |
/** | |
* Constructor function with inheritance | |
*/ | |
function Dog(name, energy, breed) { | |
Animal.call(this, energy, breed); | |
this.breed = breed; | |
} | |
Dog.prototype = Object.create(Animal.prototype); | |
Dog.prototype.bark = function() { | |
console.log('bark bark!') | |
} | |
// Reset constructor to not point to Animal, but Dog | |
Dog.prototype.constructor = Dog |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment