JSFiddle - React, Tailwind, and code Playground
HTML
<button class="speak">Speak</button>
<button class="eat">Eat</button>
<button class="walk">Walk</button>
<button class="getinfo">Get Info</button>
JavaScript
// Person Module
var Person = function ( name ) {
// Private variables and functions that only
// ..other private or public functions may access
// ..and cannot be accessed outside this Module
var age = 0,
maxAge = 20,
maxWeight = 40,
isAlive = true,
weight = 20,
name = name || 'Un-named';
var growOld = function () {
age = age + 3;
if ( age >= maxAge ) {
die();
}
}
var gainWeight = function () {
if ( weight++ >= maxWeight ) {
die();
}
}
var loseWeight = function () {
if ( weight-- <= 0 ) {
die();
}
}
var die = function () { isAlive = false; }
// All the properties and methods contained by
// ..this object being returned will be public
// ..and will be accessible in the global scope.
return {
speak : function () {
if ( !isAlive ) {
alert('Dead man can\'t speak.');
return;
}
alert(name + ': Speaking..');
growOld();
},
walk : function () {
if( !isAlive ) {
alert('Dead man can\'t walk');
return;
}
alert(name + ': Walking');
growOld();
loseWeight();
},
eat : function () {
if ( !isAlive ) {
alert('Dead man can\'t eat');
}
alert(name + ': Eating..');
gainWeight();
},
getInfo: function () {
alert("Age: " + age + "/" + maxAge + "\nWeight: " + weight + "/" + maxWeight);
}
}
}
// Create a person named Foobar
var foobar = new Person('Foobar');
$('button').on('click', function ( e ) {
var btn = $( e.target );
if( btn.hasClass('speak') ) {
foobar.speak();
} else if ( btn.hasClass('eat') ) {
...