Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/ed25518851318e32fd22a19abcf06856 to your computer and use it in GitHub Desktop.
Save smailliwcs/ed25518851318e32fd22a19abcf06856 to your computer and use it in GitHub Desktop.
Object-oriented JavaScript
if (typeof Object.create !== "function") {
Object.create = function (proto) {
function Type() { }
Type.prototype = proto;
return new Type();
};
}
function Animal(name) {
var self = this;
var energy = 100; // Private
self.name = name; // Public
// Private
function log() {
var status;
if (energy >= 100) {
status = "not tired";
} else if (energy >= 50) {
status = "somewhat tired";
} else {
status = "very tired";
}
console.log(self.name + " is " + status + ".");
}
// Privileged
self.play = function () {
console.log(self.name + " is playing.");
energy -= 1;
log();
};
// Privileged
self.eat = function () {
console.log(self.name + " is eating.");
energy += 1;
log();
self.speak();
};
}
// Public
Animal.prototype.speak = function () {
console.log(this.name + " makes a noise.");
};
var alfa = new Animal("Alfa");
console.log(alfa.energy);
console.log(alfa.log);
console.log(alfa.name);
alfa.play();
alfa.eat();
function Dog(name) {
var self = this;
Animal.call(self, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function () {
console.log(this.name + " barks.");
};
var bravo = new Dog("Bravo");
console.log(bravo instanceof Animal);
console.log(bravo instanceof Dog);
bravo.play();
bravo.eat();
undefined
undefined
Alfa
Alfa is playing.
Alfa is somewhat tired.
Alfa is eating.
Alfa is not tired.
Alfa makes a noise.
true
true
Bravo is playing.
Bravo is somewhat tired.
Bravo is eating.
Bravo is not tired.
Bravo barks.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment