JSFiddle - React, Tailwind, and code Playground
by Ajedi32
HTML
<button id="monkey">Monkey</button>
<button id="dog">Dog</button>
<button id="inheritance">Check Inheritance</button>
JavaScript
var Animal = function() {};
Animal.prototype = {
legs: 4,
makeNoise: function () {
return "noise";
}
};
var Dog = function () {};
// Notice: Dog.prototype is inheriting from Animal.prototype
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.makeNoise = function () {
var noise = "bark \n";
// Notice: calling Animal's makeNoise function with
// 'this' set to our dog object.
noise += Animal.prototype.makeNoise.call(this);
return noise;
};
var Monkey = function () {};
// Notice: Monkey.prototype is inheriting from Animal.prototype
Monkey.prototype = Object.create(Animal.prototype)
Monkey.prototype.legs = 2;
Monkey.prototype.makeNoise = function () {
var noise = "weird monkey sound \n";
// Notice: calling Animal's makeNoise function with
// 'this' set to our monkey object.
noise += Animal.prototype.makeNoise.call(this);
return noise;
};
$("#monkey").click(function () {
var monkey = new Monkey();
var result = "Legs: " + monkey.legs + "\n";
result += "Noise: " + monkey.makeNoise();
alert(result);
});
$("#dog").click(function () {
var dog = new Dog();
var result = "Legs: " + dog.legs + "\n";
result += "Noise: " + dog.makeNoise();
alert(result);
});
$("#inheritance").click(function () {
var dog = new Dog();
var monkey = new Monkey();
var result = 'dog instanceof Dog = ' + (dog instanceof Dog) + "\n" +
'dog instanceof Animal = ' + (dog instanceof Animal) + "\n" +
'dog instanceof Monkey = ' + (dog instanceof Monkey) + "\n" +
'monkey instanceof Monkey = ' + (monkey instanceof Monkey) + "\n" +
'monkey instanceof Animal = ' + (monkey instanceof Animal) + "\n" +
'monkey instanceof Dog = ' + (monkey instanceof Dog) + "\n";
alert(result);
});