reading-notes

Pre-work Class Notes (301)

ES6 Classes1

Modeling

Ex. model an animal

const Animal = function(name, legs) { this.name = name; this.legs = legs; }

Animal.prototype.walk = function() { this.isWalking = true; }

let puppy = new Animal(‘blake’, 4); console.log(puppy) //Animal {name:’blake’, legs: 4}

puppy.walk(); console.log(puppy) //Animal {name:’blake’, legs: 4, isWalking:true}

const Animal = function(name, legs) { this.name = name; this.legs = legs; this.isEating= function () { this.isEating = true; } } puppy.eat(); console.log(puppy); //Animal {name:’blake’, legs: 4, eat: [function], isWalking:true, isEating:true}

const Animal = function(name, legs) { Animal.call(this, name, legs); //call the Animal constructor with this }

Dog.prototype = Object.create(Animal.prototype); // let the Dog have access too ALL Animal prototypes

let puppy = new Dog(‘blake’, 4); puppy.walk(); puppy.eat(); console.log(puppy) //Animal {name:’blake’, legs: 4, eat: [function], isWalking:true, isEating:true}

console.log(puppy instanceof Animal); //true console.log(puppy instanceof Dog); //true

Reproduce the code above using a Class

class Animal { constructor(name, legs) { this.name = name; this.legs = legs; }

walk() { //no need to tell JS that this is a function this.isWalking = true; }

eat() { this.isEating = true; } }

let rosie = new Animal(‘rosie’, 4); cosole.log(rosie) //Animal{ name:’rosie’,legs:4}

rosie.walk(); rosie.eat(); cosole.log(rosie) //Animal{ name:’rosie’,legs:4, isWalking: true, isEating: true}

Make a new class from the Animal class

class Dog extends Animal { } let rosie = new Animal(‘rosie’, 4); rosie.walk(); rosie.eat(); cosole.log(rosie) //Dog{ name:’rosie’,legs:4, isWalking: true, isEating: true}

class Dog extends Animal { speak(){ console.log(‘Woof!’); } } //do not need to say call, the extend does it all rosie.speak(); console.log(rosie) // Dog{ name:’rosie’,legs:4, isWalking: true, isEating: true} Woof!

class Dog extends Animal {

constructor (name, legs, furType){ super(name,legs); //super says to use these attributes to create an instance, and then add everthing else to just this subclass this.furType = furType; }

speak(){ console.log(‘Woof!’); } } let rosie = new Animal(‘rosie’, 4, ‘Short Hair’); rosie.walk(); rosie.eat(); rosie.speak(); console.log(rosie) // Dog{ name:’rosie’,legs:4, furType: ‘Short Hair’, isWalking: true, isEating: true} Woof!

Back to main page

References

  1. https://www.youtube.com/watch?v=9Yc5J3Ap9-4