Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Last active May 18, 2021 02:49
Show Gist options
  • Save lokshunhung/3bcfdf17c11b6e82f18c00264915bd46 to your computer and use it in GitHub Desktop.
Save lokshunhung/3bcfdf17c11b6e82f18c00264915bd46 to your computer and use it in GitHub Desktop.
ES5 prototype inheritance
function Animal(nickname, gender) {
this.nickname = nickname;
this.gender = gender;
}
Animal.prototype.getName = function () {
return this.nickname;
};
Animal.prototype.getGender = function () {
if (this.gender === "M") return "boy";
if (this.gender === "F") return "girl";
}
Animal.prototype.greet = function () {
var statement = "I'm " + this.getName() + " and I'm a " + this.getGender();
console.log(statement);
};
function Cat(nickname, gender, ownerName) {
Animal.call(this, nickname, gender);
this.ownerName = ownerName;
}
Cat.prototype = (function () {
// need value of `{ constructor: Cat, __proto__: Animal }`
function CatExtendsAnimal() {}
CatExtendsAnimal.prototype = Animal.prototype;
var catPrototype = new CatExtendsAnimal();
catPrototype.constructor = Cat;
return catPrototype;
})();
Cat.prototype.meow = function () { console.log("meow") };
Cat.prototype.getName = function() {
var originalName = Animal.prototype.getName.call(this);
return this.ownerName + "'s " + originalName;
};
var c = new Cat("mittens", "F", "mike");
c.meow();
c.greet();
console.log(c.getName())
function Dog(nickname, gender, ownerName) {
Animal.call(this, nickname, gender);
this.ownerName = ownerName;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function () { console.log("woof") };
Dog.prototype.getName = function () {
var originalName = Animal.prototype.getName.call(this);
return originalName + " the dog";
}
var d = new Dog("bobby", "M", "billy");
d.greet();
// ref:
// https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
// https://medium.com/developers-arena/javascript-classes-inheritance-and-prototype-chaining-es5-and-es6-way-4b8e9416702b
// https://medium.com/@dange.laxmikant/simplified-inheritance-in-js-es5-way-60b4ff19b008
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment