Published
Edited
Jun 20, 2020
Insert cell
Insert cell
Insert cell
class Animal {
constructor(name, species, sex) {
this.species = species;
this.sex = sex;
this.name = name;
this.stomach = [];
}

eat(food) {
this.stomach.push(food);
}

poop() {
const randomAmount = Math.round(Math.random() * (this.stomach.length - 1));
let doggyBag = [];
for (var i = 0; i < randomAmount; i++) {
doggyBag.push(this.stomach.pop());
}
return doggyBag;
}

introduce() {
return `Hi, my name is ${this.name}. I'm a ${this.sex} ${this.species}.`;
}
}
Insert cell
Insert cell
{
const matt = new Animal("Matt", "Human", "male");

matt.eat("pizza");
matt.eat("chocolate");
matt.eat("beef");

matt.poop();

return matt.stomach;
}
Insert cell
Insert cell
class Dog extends Animal {
constructor(name, sex, breed) {
super(name, "dog", sex); //"super" refers to the "superclass," or the class we are extending
this.breed = breed;
}

introduce() {
// extend superclass method
return super.introduce() + " Woof woof!";
}

bark() {
return "woof";
}
}
Insert cell
Insert cell
chase = new Dog("Chase", "male", "chihuahua")
Insert cell
chase.introduce()
Insert cell
chase.bark()
Insert cell
chase.breed
Insert cell
Insert cell
{
class Robot {
constructor() {
// static property
Robot.totalUnits = Robot.totalUnits + 1 || 1;

this.serialNo = Robot.totalUnits;
}

introduce() {
return "Hello. I am unit " + this.serialNo + " of " + Robot.totalUnits;
}
}

var robo1 = new Robot();
var robo2 = new Robot();
var robo3 = new Robot();
var robo4 = new Robot();

return robo1.introduce();
}
Insert cell
Insert cell
class Stat {
constructor(stat) {
this.stat = stat;
}

static combineStats(stat1, stat2) {
return new Stat(stat1.stat + stat2.stat);
}
}
Insert cell
Insert cell
Insert cell
statA.stat
Insert cell
statA.combineStats(statA, statB)
Insert cell
Stat.combineStats(statA, statB)
Insert cell
Insert cell
clif = new Dog('Clif', 'male', 'Big Red')
Insert cell
clif instanceof Dog
Insert cell
clif instanceof Animal
Insert cell
Dog instanceof Animal // why is this false?
Insert cell
Insert cell
class Robot {
//write code here
}
Insert cell
Insert cell
Insert cell
class FastRobot /*code here*/ {
//code here
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more