Created
September 22, 2020 15:24
-
-
Save smailliwcs/ed25518851318e32fd22a19abcf06856 to your computer and use it in GitHub Desktop.
Object-oriented JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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