meesie1
3/9/2020 - 1:42 PM

Object maken in js

const animalMethods = {
  eat(amount){
    console.log(this.name + " is eating");
    this.energy += amount;
  },
  sleep(){
    console.log(this.name + " is sleeping");
    this.energy = 100;
  }
}


function Animal(name, energy){
  // Object.create allows you to create an object and whenever there’s a failed property lookup on that object, 
  // it can consult another object to see if that other object has the property
  let animal = Object.create(animalMethods);
  animal.name = name;
  animal.energy = energy;
  animal.eat = animalMethods.eat;
  
  return animal;
}

const leo = Animal('Leo', 50);
leo.sleep();