interfaces/topic_5/example1/script.js

32 lines
642 B
JavaScript

function Animal(name, energy) {
let obj = Object.create(Animal.prototype);
obj.name = name;
obj.energy = energy;
return obj;
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`);
this.energy += amount;
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`);
this.energy += length;
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`);
this.energy -= length;
}
const leo = Animal("Leo", 7);
leo.sleep(8);
leo.eat(2);
leo.play(10);
const bob = Animal("Bob", 3);
bob.sleep(8);
bob.eat(2);
bob.play(10);